Updating an array of objects within an array using another array of objects

There are two JavaScript Arrays:

let x = [
    {
        id: 'Abc',
        children: [
            {
                id: 12,
                name: 'john'
            }, {
                id: 13,
                name: 'dow'
            }
        ]
    }, {
        id: 'xyz',
        children: [
            {
                id: 123,
                name: 'jack'
            }, {
                id: 134,
                name: 'abc'
            }
        ]
    }
]
let y = [
    {
        id: 12,
        name: 'mac'
    }, {
        id: 13,
        name: 'dow'
    }, {
        id: 123,
        name: 'Tom'
    }, {
        id: 134,
        name: 'abc'
    }
]

The goal is to update Array x with the data in Array y, resulting in the following updated array:

[
    {
        id: 'Abc',
        children: [
            {
                id: 12,
                name: 'mac'
            }, {
                id: 13,
                name: 'dow'
            }
        ]
    }, {
        id: 'xyz',
        children: [
            {
                id: 123,
                name: 'Tom'
            }, {
                id: 134,
                name: 'abc'
            }
        ]
    }
]

An attempt was made using this solution:

x.map((a, index)=>{
    a.children.map((b, i)=>{
        // console.log('update')
        y.find(o => o.id === b.id) || b;
    })
})

However, the result was an undefined value. Further exploration for a solution has been unsuccessful.

Answer ā„–1

const updatedArray = x.map((a, index)=>{
    a.children.map((b, i)=>{
        // console.log('update')
        y.find(o => o.id === b.id) || b;
    })
})

Before we proceed, let's address a common error made when using an array function: Curly braces {} are not necessary for single-line statements; however, the return keyword must be explicitly included.

arr.filter(v => v === 2) is equivalent to

arr.filter(v => {return v === 2})
. Omitting return will result in filter() returning an empty array.

Here's a concise solution :

const updatedResult = x.map((a, index) => ({ ...a, children: a.children.map((b, i) => y.find(o => o.id === b.id) || b) }));

Snippet of code :

let x = [
    {
        id: 'Abc',
        children: [
            {
                id: 12,
                name: 'john'
            }, {
                id: 13,
                name: 'dow'
            }
        ]
    }, {
        id: 'xyz',
        children: [
            {
                id: 123,
                name: 'jack'
            }, {
                id: 134,
                name: 'abc'
            }
        ]
    }
]
let y = [
    {
        id: 12,
        name: 'mac'
    }, {
        id: 13,
        name: 'dow'
    }, {
        id: 123,
        name: 'Tom'
    }, {
        id: 134,
        name: 'abc'
    }
]

const updatedResult = x.map((a, index) => 
  ({ ...a, children: a.children.map((b, i) => y.find(o => o.id === b.id) || b) }));

console.log(updatedResult);

Answer ā„–2

To start, create a lookup object for y and then utilize the map function to iterate through the children of x

let x = [
  {
    id: "Abc",
    children: [
      {
        id: 12,
        name: "john",
      },
      {
        id: 13,
        name: "dow",
      },
    ],
  },
  {
    id: "xyz",
    children: [
      {
        id: 123,
        name: "jack",
      },
      {
        id: 134,
        name: "abc",
      },
    ],
  },
];
let y = [
  {
    id: 12,
    name: "mac",
  },
  {
    id: 13,
    name: "dow",
  },
  {
    id: 123,
    name: "Tom",
  },
  {
    id: 134,
    name: "abc",
  },
];

const lookupY = {};
y.forEach(({ id, name }) => (lookupY[id] = name));

const newX = x.map(({ id, children }) => ({
  id,
  children: children.map((item) => ({ id:item.id, name: lookupY[item.id] })),
}));

console.log(newX)

Answer ā„–3

Initially, remember to include the return statement within the callback function. Also ensure that you do not lose any other keys in the object.

const x = [
  {
    id: 'Abc',
    children: [
      {
        id: 12,
        name: 'john'
      }, {
        id: 13,
        name: 'dow'
      }
    ]
  }, {
    id: 'xyz',
    children: [
      {
        id: 123,
        name: 'jack'
      }, {
        id: 134,
        name: 'abc'
      }
    ]
  }
];
const y = [
  {
    id: 12,
    name: 'mac'
  }, {
    id: 13,
    name: 'dow'
  }, {
    id: 123,
    name: 'Tom'
  }, {
    id: 134,
    name: 'abc'
  }
];

const newArr = x.map((a, index) => {
  const children = a.children.map((b, i) => {
    return y.find(o => o.id === b.id) || b;
  })
  return { ...a, children };
})

console.log(newArr);

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

What is the best way to activate a JavaScript function once a page has finished loading?

Hey there! I have a webpage with 2 text input fields and a DIV element. The first input field is for user input, while the second one is readonly. When the user hits Enter in the first input field, a new page loads into the DIV based on the query result f ...

Tips for creating a navigation bar item that displays a component depending on its active state

Trying to enhance the modularity of my code but facing difficulties. I have a tab bar and I want to render a specific component based on the clicked nav/tab item. Struggling with passing props properly, as the current code only recognizes the children valu ...

Swipe JS: tap on the edge to view the next item

Currently utilizing Swipe JS to generate a full-screen image gallery and aiming to incorporate the functionality of clicking on the left or right edge to navigate between the previous and next slides. An attempt was made to create absolutely positioned a ...

Creating an AJAX function to display a popup window for users who are already registered - here's how!

I am currently working on a dropwizard-java project. Whenever users click the subscribe button, it displays a thank you message for subscribing and then checks if the user is already registered. I would like to have a pop-up window immediately show whethe ...

What is the best way to break a string based on a specific delimiter?

I'm trying to retrieve data from the API at and the element I'm working with is in the format of [ 12 +14 +2 +8 ]. My goal is to extract each individual value from this string and display them separately in an array. Initially, I attempted to u ...

Click-o-Meter: Tracking Button Presses

Iā€™m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet: <?php $counterFile = 'path/to/counter.txt' ; ...

Executing a Cron Job several times daily, each and every day

This is my current code snippet: const CronJob = require('cron').CronJob; new CronJob({ cursoronTime: '* * * * *', // every minute onTick: async function() { console.log(&ap ...

Strategies for efficiently parsing JSON in HTML using AngularJS

I have received this JSON format and I am looking to extract the message and username fields. How can I achieve this? Also, I want to format the date in Y-m-d format. I tried using ng-repeat but couldn't print the data. Can someone please help me disp ...

Attempting to streamline this particular JavaScript function

I have been struggling with a function that I believe could be written more effectively. My goal is to simplify it while still maintaining its functionality. function changeLetters(text) { text = text.toLowerCase(); for (var i = 0; i < text.length; ...

The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project. Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is ...

How to find a collision between a spherical object and a triangular shape in a three

In my research, I am exploring the possibility of detecting collisions between a triangle and a sphere in three.js. Currently, I have devised a method using the raycaster and the sphere's vertices. However, this approach has proven to be unreliable a ...

Manipulating rows [using an input field] within a table

As someone new to JavaScript, I tried my hand at coding the following piece after tweaking a tutorial I stumbled upon. The aim was to have rows with input fields added and removed within a table, but unfortunately, nothing happens when running the code. ...

Tips on how to Parse Multiple Json Files in Java

When I use the code provided below, I receive {"User_id":"test123","Password":"test225"}{"User_id":"test122","Password":"asds"} a JSON format that is considered invalid. What I actually want is the following JSON format but am having trouble creating it ...

Tips for inserting a personalized image or icon into the ANTD Design menu

Can anyone help me figure out how to replace the default icons with a custom image or icon in this example: https://ant.design/components/layout/#components-layout-demo-side I attempted to do it by including the following code: <Menu.Item to="/" key=" ...

Store text in a C# array by reading individual words

I have been struggling to populate an array with a list of words. Despite going through various tutorials and seeking help on forums, I am still unable to make it work. It seems like there is a simple error that I am overlooking but I just can't seem ...

Navigate to link based on selected option in Bootstrap select menu

How can I make a page redirection based on the selected option value from a bootstrap select? Here is the HTML code: <select class="selectpicker"> <option value="https://example.com/">Home</option> <option value="https://exam ...

Tips for parsing a json decoded array using php

I am currently working with an array structure that is proving to be a bit challenging. Here is the array in question: Array ( [0] => stdClass Object ( [aure] => test [menu] => stdClass Object ( ...

How can I implement Before() and After() hooks within a hooks.js file for a Selenium and JavaScript project?

Within my Selenium JS / Cucumber framework, I have incorporated Before() & After() functions to handle the setup and tear down of my webdriver. To manage these functions, I decided to organize them in my customSteps.js file alongside other cucumber st ...

Ways to create a group label to modify various textboxes when a click event occurs

Is it possible to change multiple textboxes with corresponding labels after a click event? Issue: The current output only displays the value of the last textbox. $(function () { $('a.edit').on('click', function (e) { e.pre ...

Having trouble connecting to Docker? The webpage at localhost seems to be unresponsive and is not providing any data. Error: ERR_EMPTY_RESPONSE

Currently in the process of mastering docker, kafka, and python. My objective is to leverage python for extracting data from json files and transmitting them to kafka. The setup seems to be functioning properly, but I'm facing challenges with viewin ...