What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format:

  • Healthcare
    -- Insights driven by data for improved healthcare
    -- Urban Analytics

  • Transport
    -- Urban Analytics

  • Cities
    -- Urban Analytics

I have attempted to iterate over 'expertise' and 'text', but I am having difficulty getting them to work together to achieve the desired output within console.log

Any assistance or guidance would be greatly appreciated.

    var items = [{
            "item": {
                "id": 0,
                "sector": 'Data',
                "expertise": ["Healthcare"],
                "text": "Insights driven by data for improved healthcare"
            }
        },
        {
            "item": {
                "id": 1,
                "sector": 'Data',
                "expertise": ["Healthcare", "Transport", "Cities"],
                "text": "Urban Analytics"
            }
        }
    }];

    var array = [];

    for (var i = 0; i < items.length; i++) {

        var arr = [{
            'title': items[i].item.sector,
            'items': []
        }];

        for (var j = 0, b = items[i].item.expertise.length; j < b; j++) {
            if (items[i].item.expertise[j] == expertise) {

                arr[0]['items'].push({
                    'list': items[i].item.text
                });

            }
        }

        array.push(arr);

    }

    console.log(array);

Answer №1

To begin, I suggest creating an object containing relevant expertise and text lists, then displaying the output in your preferred format. Here is a simple example:

var items = [{
  "item": {
    "id": 0,
    "sector": 'Technology',
    "expertise": ["Cybersecurity"],
    "text": "Protecting digital assets"
  }
}, {
  "item": {
    "id": 1,
    "sector": 'Technology',
    "expertise": ["Cybersecurity", "Data Privacy", "AI"],
    "text": "Securing sensitive information"
  }
}]
    
const obj = items.reduce((res, { item }) => {
  item.expertise.forEach(e => {
    res[e] = res[e] || []
    if(res[e].indexOf(item.text) < 0){ res[e].push(item.text) }
  })
  return res
}, {})

Object.keys(obj).forEach(k => {
  console.log(k)
  obj[k].forEach(text => console.log(`-- ${text}`))
})

Answer №2

Utilizing the map function is recommended in this case

const updatedArray = items.map(item => ({
    title: item.item.category,
    details: [...item.item.skills, {
        category: item.item.details
    }]
});

Answer №3

Below is a different method using the reduce() function, along with destructuring and the spread operator

const itemsList = [
  {
    "item": {
      "id": 0,
      "sector": 'Technology',
      "expertise": ["AI"],
      "description": "Artificial Intelligence advancements"
    }
  },
  {
    "item": {
      "id": 1,
      "sector": 'Technology',
      "expertise": ["AI", "Blockchain"],
      "description": "Cutting-edge technology innovations"
    }  
  }
];

let result = itemsList.reduce((accumulator, {item: {expertise, description}}) =>
{
     expertise.forEach(item => accumulator[item] = [...(accumulator[item] || []), description]);
     return accumulator;
}, {});


Object.entries(result).forEach(([key, value]) =>
{
    console.log(key + "\n->" + value.join("\n->"));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

A step-by-step guide on utilizing the v-for index loop to showcase a nested JSON array

My JSON Array has the following structure: items: [ { ID: 11, UserID: "test.com", UserRole: "user", timeStamp: "2021-03-23T15:54:02.125578", dialogs: [ { "Bot" ...

Setting up an i18n project in AngularJS

I just embarked on my angularjs journey yesterday with little to no prior knowledge about it. My initial goal is to centralize all the labels for my UI in a file (to facilitate swapping them out for i18n). As far as I know, this can be achieved by importi ...

Use JavaScript to generate an HTML element that has an attribute mirroring its text content

Trying to figure out how to create an HTML element similar to this: <option value="Replaced">by this</option> For example: <option value="ThisIsTest">ThisIsTest</option> UPDATE Using jQuery, I need to achieve something like thi ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

How can I update a property within an object in a sequential manner, similar to taking turns in a game, using React.js?

I am currently working on a ReactJs project where I am creating a game, but I have encountered an issue. I need to alternate turns between players and generate a random number between 1 and 10 for each player, storing this random number inside their respec ...

Exploring the functionality of the Angular snackbar feature

I have created a simple snackbar with the following code: app.component.ts: ngOnInit(){ this.dataService.valueChanges.pipe( filter((data) => data === true), switchMap(() => { const snackBarRef = this.matSnackBar.open ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Utilizing JavaScript Modules to Improve Decoupling of DOM Elements

Currently, I am tackling portions of a complex JavaScript application that heavily involves DOM elements. My goal is to begin modularizing the code and decoupling it. While I have come across some helpful examples, one particular issue perplexes me: should ...

"Revolutionizing the way we navigate: Angular's innovative

Presently, my focus is on incorporating route transitions into my project. I've employed a component that appears on click and triggers the corresponding service function: routeTransition(destination) { if (this.router.url !== destination) { t ...

Merging text and a JSON object to retrieve the information

Having some trouble with a JSON object and retrieving values. This is the syntax that works for getting the data I need. dataJSON.companies[0].fields.Internet.length I want to dynamically evaluate the object using a string variable, like this... var me ...

How can I integrate a timer into an Angular carousel feature?

I have put together a carousel based on a tutorial I found on a website. Check out the HTML code for my carousel below: <div class="row carousel" (mouseover)="mouseCheck()"> <!-- For the prev control button ...

Numerous documents within a JavaScript application

As a newcomer to JavaScript, I've been experimenting with the language to enhance my understanding. One aspect that puzzles me is how developers organize large JavaScript programs. In languages like Java, breaking down code into smaller files is commo ...

Unexpectedly, a significant ngrx createEffect leads to an unusual error following an update, but the issue vanishes when certain code snippets like tap or filter are disabled

I have been in the process of upgrading a massive Angular 12 project to Angular 13 and have completed several steps. One significant change was the rewriting of Effects using a newer approach like createEffect(() => instead of @Effect However, during ...

deactivating image mapping on mobile media screens

I'm looking to disable my image map on mobile screens using media queries. I've attempted to include some javascript in the head of my html file, but I encountered an error: <script src="http://code.jquery.com/jquery-1.11.3.min.js"></s ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

Resolve problems with implementing dynamic routes in Next.js

I have been learning about Next.js and I am struggling with understanding how to set up dynamic routing. I have the following setup: https://i.stack.imgur.com/uBPdm.png https://i.stack.imgur.com/YYSxn.png "use client" import React from "reac ...

Could one potentially generate new static files in Nextjs without needing to rebuild the entire app?

After recently beginning to utilize NextJs' getStaticProps feature, I have found that the static files generated at build time are quite impressive. However, my content is not static and requires updates without having to rebuild the entire app each t ...

Can you guide me on incorporating a date input with ngModel?

I have a date input field set up as follows: <input [(ngModel)]="value" type="text" class="form-control"> Can someone explain how I can display and submit the value correctly? The user's input should be formatted as dd/MM/yyyy, while t ...

The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files: /app/view1/view1.js 'use strict'; angular.mod ...