A
A
asd dsa2020-05-12 23:54:38
JavaScript
asd dsa, 2020-05-12 23:54:38

How to make one with the necessary properties from two data collections?

I have two data collections, I need to get two properties with values ​​from the first collection and two properties with values ​​from the other collection and make one collection from them with 4 properties that will correspond to the values, both collections have the same id field, which is not needed in the new collection, but by which you can compare, please tell me how to solve the problem?

const collection1 = [
{id: test1, value: "value1"  status: "status1"}, 
{id: test1, value: "value11"  status: "status11"}, 
{id: test2, value: "value2"  status: "status2"}, 
{id: test2, value: "value22"  status: "status22"}, 
{id: test3, value: "value3"  status: "status3"}, 
{id: test3, value: "value33"  status: "status33"}
]
const collection2 = [
{id: test1, text: "text for value 1"  secondaryText: " secondary text for value 1"}, 
{id: test2, text: "text for value 2"  secondaryText: " secondary text for value 2"}, 
{id: test3, text: "text for value 3"  secondaryText: " secondary text for value 3"}
]


This is how the collection should look like:

const collection3 = [
{value: "value1", status: "status1", text: "text for value 1"  secondaryText: " secondary text for value 1"}, 
{value: "value11",  status: "status11", text: "text for value 1",  secondaryText: " secondary text for value 1"}, 
{value: "value2",  status: "status2", text: "text for value 2",  secondaryText: " secondary text for value 2" }, 
{value: "value22",  status: "status22", text: "text for value 2",  secondaryText: " secondary text for value 2"}, 
{value: "value3",  status: "status3", text: "text for value 3",  secondaryText: " secondary text for value 3"}, 
{value:"value33",  status: "status33", text: "text for value 3"  secondaryText: " secondary text for value 3"}
]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-05-13
@yaNastia

const obj2 = Object.fromEntries(arr2.map(n => [ n.id, n ]));
const arr3 = arr1.map(n => ({ ...n, ...obj2[n.id] }));

V
Vearodev, 2020-05-13
@Vearodev

Damp, but it works, guess what

const collection3 = []

collection1.forEach((item, i) => {
  const found_prop = collection2.find(p => p.id === item.id)
  collection3.push(Object.assign(item, found_prop))
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question