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

The issue of JQuery Mobile not recognizing HREF links when combined with Javascript

I am facing a challenge with my button functionality that is supposed to open a panel. However, there seems to be an interference caused by my JavaScript code. The panel contains a notifications center and in order to retrieve the notifications, I have to ...

Choosing a value from a dropdown automatically based on the selection of a specific value from another dropdown

Currently, I am working on a project that involves selecting a value from a dropdown menu based on the selection from another dropdown menu. var gender1 = document.querySelector("#gender1"); var gender2 = document.querySelector("#gender2"); gender1.add ...

The Typescript SyntaxError occurs when attempting to use an import statement outside of a module, typically within a separate file that contains

I am currently developing a Minecraft bot using the mineflayer library from GitHub. To make my code more organized and reusable, I decided to switch to TypeScript and ensure readability in my project structure (see image here: https://i.stack.imgur.com/znX ...

Getting started with `sessionStorage` in a React application

Currently, I am attempting to save an item in sessionStorage prior to rendering. The code snippet I have looks like this: componentWillMount() { sessionStorage.setItem("isUserLogged", false); } However, I encountered an error stating th ...

What strategies can I implement to ensure my modal dialog box remains responsive? Adjusting the window size causes the modal box to malfunction and lose its structure

Whenever I adjust the size of the browser window, the elements inside the modal box become misaligned. HTML <div class='modal'> <div class='modal-content'> </div> </div> Below is the CSS for the modal ...

Obtain a byte array from an AngularJs controller

In my Angular controller, I am working with a byte array. When the download button is clicked in the view, I want to trigger the browser's download/saveAs dialog with 'report.pdf' as the pre-populated filename and PDF as the file type. After ...

The onmessage event in the websocket client seems to be malfunctioning and is not triggering

In my implementation using node.js, I have set up a websocket server and client. The handshake process between the server and client appears as follows: Request URL: ws://localhost:8015/ Request Method: GET Status Code: 101 Switching Protocols Request ...

Checking the validity of date inputs - microservice for timestamps

I'm encountering an issue while attempting to validate my date input. I've tried using moment js, but it seems there's a problem. The error message "date invalid" keeps popping up! Here is the code snippet: app.get("/api/timestamp/:date_s ...

Expanding the functionality of Element.prototype, problem related to anchor

Consider the following code: A JavaScript (JS) Snippet Element.prototype.changeInnerText = function(str) { this.textContent = str; return this; } let divElement = document.createElement('div').changeInnerText('new div text'); / ...

Exploring the power of Vue's v-for directive with nested

I have an array within an array that I want to showcase in a table. However, I am struggling to display my nested array correctly. Here is how my data set looks: [ { "dd":"February", "md":[ { "dag":"2020-02-01" }, { "d ...

Is it possible to achieve real-time two-way data binding in a reactive form by passing values from one formgroup to another formgroup? If so, how

There are 2 FormGroups named orderForm and parcelForm on a page. The parcelForm is generated dynamically within a FormArray. In the parcelForm, there are FormControls like net_weight and gross_weight, while the OrderForm has FormControls such as total_net_ ...

Is there a way to identify the duplicated input element values using jquery?

Just starting out in the world of web development and jQuery. I have an input element that has been bound with a blur event. Here's the code snippet: // Here are my input elements: <input class="input_name" value="bert" /> <input class="inp ...

Attributes of the host element in Angular 1.5 components

I am seeking a way to customize attributes on the host element for Angular 1.5 components. What is the purpose? I would like to assign a class to a component in order to apply specific styles. For example, if the parent component has display: flex set, ...

Leverage the power of Typescript to flatten a JSON model with the help of Class

Currently, I'm exploring how to utilize the class transformer in TypeScript within a Node.js environment. You can find more information about it here: https://github.com/typestack/class-transformer My goal is to flatten a JSON structure using just on ...

Merging two promises into a single promise in Angular

In my application, I am facing a challenge with implementing a method named loadAll. What I need to accomplish is to make calls to 2 different HTTP methods in order to load the necessary data. Both of these methods return promises. However, when I attem ...

Nested interfaces can utilize sum types

An example showcasing the use of sum types: interface Cash { amount: number, type: 'cash' } interface Card { amount: number, type: 'card', cardNumber: string } type Payment = Cash | Card const displayPayment = (payment: Pay ...

How can I submit a form or retrieve HTML content using JavaScript without using an iframe?

Background: My current job involves transcribing paper reports using a webapp that is quite old and cannot be updated or connected to a database directly. The system only checks for duplicate unique IDs once the entire form is submitted. This often leads ...

Difficulty encountered while deploying a React application on Netlify

I followed the instructions on a Medium link to deploy my React application on Netlify: To set up the production mode, I utilized an express server for defining build scripts. After creating the build scripts on my local machine, I uploaded them to the Ne ...

The Debate: Single Javascript File vs. Lazy Loading

Imagine you're working on a massive javascript-powered web application with minimal page refreshes in mind, containing around 80-100MB of unminified javascript to give an idea of its scale. The theory is that by lazy-loading your javascript files, yo ...

How to effectively manage radio buttons in Angular 6

Here are some questions I have listed below. public QandAList = [ { question:{ id: "Q1", query:"What is the capital of France?" }, options:[ { id: "opt1", text: "Paris" }, ...