0

I want to merge two array of objects. Following are the two arrays:-

let listing=[
{name:'name1',age:14,email:'[email protected]'},
{name:'name2',age:15,email:'[email protected]'},
{name:'name3',age:13,email:'[email protected]'},
{name:'name4',age:12,email:'[email protected]'},
{name:'name5',age:15,email:'[email protected]'},
{name:'name6',age:16,email:'[email protected]'},
{name:'name7',age:12,email:'[email protected]'},
{name:'name8',age:16,email:'[email protected]'},
{name:'name2',age:15,email:'[email protected]'},
{name:'name9',age:17,email:'[email protected]'},
]

let info=[
{name:'name1',class:7,roll_no:4},
{name:'name3',class:6,roll_no:10},
{name:'name2',class:8,roll_no:2},
{name:'name5',class:8,roll_no:18},
{name:'name6',class:9,roll_no:23},
{name:'name7',class:5,roll_no:9},
{name:'name8',class:9,roll_no:13},
{name:'name2',class:8,roll_no:4},
{name:'name8',class:9,roll_no:13},
{name:'name2',class:8,roll_no:4},
]

Output should be in this form:-

let resultant_array=[
    {name:'name1',age:14,email:'[email protected]',class:7,roll_no:4},
    {name:'name2',age:15,email:'[email protected]',class:8,roll_no:2},
    {name:'name3',age:13,email:'[email protected]',class:6,roll_no:10},
    {name:'name5',age:15,email:'[email protected]',class:8,roll_no:18},
    {name:'name6',age:16,email:'[email protected]',class:9,roll_no:23},
    {name:'name7',age:12,email:'[email protected]',class:5,roll_no:9},
    {name:'name8',age:16,email:'[email protected]',class:9,roll_no:13},
    {name:'name2',age:15,email:'[email protected]',class:8,roll_no:4},
    {name:'name8',age:16,email:'[email protected]',class:9,roll_no:13},
    {name:'name2',age:15,email:'[email protected]',class:8,roll_no:4},
    ]

I want that all the objects specified in info array where name is same in both the objects should be included in new array and the objects should be inserted in the same format as listing array.

resultant_array=listing.map(x => Object.assign(x, info.find(y => y.name== x.name))); displays only first match. If i use filter then all the matched objects are inserted in one element only.

0

2 Answers 2

0
const result = []
listing.forEach(x => {
  result.push(Object.assign(x, info.find(y => y.name== x.name) || {}))
})
Sign up to request clarification or add additional context in comments.

Comments

0

This will work on any number of matching keys, without having specify the object property you are trying to match.

let resultant_array = listing.map((item, i) => Object.assign({}, item, info[i]));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.