I have this array of objects, within it I have another array of objects:
[
{
id: 1,
country: [
{
id: "5a60626f1d41c80c8d3f8a85"
},
{
id: "5a6062661d41c80c8b2f0413"
}
]
},
{
id: 2,
country: [
{
id: "5a60626f1d41c80c8d3f8a83"
},
{
id: "5a60626f1d41c80c8d3f8a84"
}
]
}
];
How to get flat array of country like this:
[
{ id: "5a60626f1d41c80c8d3f8a85" },
{ id: "5a6062661d41c80c8b2f0413" },
{ id: "5a60626f1d41c80c8d3f8a83" },
{ id: "5a60626f1d41c80c8d3f8a84" }
];
without using a forEach and a temp variable?
When I did:
(data || []).map(o=>{
return o.country.map(o2=>({id: o2.id}))
})
I got the same structure back.
Latest edit
All modern JS environments now support Array.prototype.flat and Array.prototype.flatMap
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.flatMap(
(elem) => elem.country
)
)
Old answer
No need for any ES6 magic, you can just reduce the array by concatenating inner country arrays.
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.reduce(
(arr, elem) => arr.concat(elem.country), []
)
)
If you want an ES6 feature (other than an arrow function), use array spread instead of the concat method:
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.reduce(
(arr, elem) => [...arr, ...elem.country], []
)
)
Note: These suggestions would create a new array on each iteration.
For efficiency, you have to sacrifice some elegance:
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.reduce(
(arr, elem) => {
for (const c of elem.country) {
arr.push(c);
}
return arr;
}, []
)
)
const raw = [
{
id: 1,
country: [
{
id: "5a60626f1d41c80c8d3f8a85"
},
{
id: "5a6062661d41c80c8b2f0413"
}
]
},
{
id: 2,
country: [
{
id: "5a60626f1d41c80c8d3f8a83"
},
{
id: "5a60626f1d41c80c8d3f8a84"
}
]
}
];
const countryIds = raw
.map(x => x.country)
.reduce((acc, curr) => {
return [
...acc,
...curr.map(x => x.id)
];
}, []);
console.log(countryIds)
This, works, just concat the nested arrays returned by your solution
let arr = [{ "id": 1,
"country": [{
"id": "5a60626f1d41c80c8d3f8a85",
},
{
"id": "5a6062661d41c80c8b2f0413",
}
]
},
{
"id": 2,
"country": [{
"id": "5a60626f1d41c80c8d3f8a83",
},
{
"id": "5a60626f1d41c80c8d3f8a84",
}
]
}
];
//If you want an array of country objects
console.log([].concat.apply(...(arr || []).map(o=> o.country)))
//If you can an array od country ids
console.log([].concat.apply(...(arr || []).map(o=> o.country.map(country => country.id))))
Ayush Gupta's solution will work for this case. But I would like to provide other solution.
const arr = [
{
id: 1,
country: [
{
id: '5a60626f1d41c80c8d3f8a85'
},
{
id: '5a6062661d41c80c8b2f0413'
}
]
},
{
id: 2,
country: [
{
id: '5a60626f1d41c80c8d3f8a83'
},
{
id: '5a60626f1d41c80c8d3f8a84'
}
]
}
];
const ids = arr.reduce(
(acc, {country}) => [
...acc,
...country.map(({id}) => ({
id
}))
],
[]
);
console.log(ids);
For JSON string data, it can be done during parsing too :
var ids = [], json = '[{"id":1,"country":[{"id":"5a60626f1d41c80c8d3f8a85"},{"id":"5a6062661d41c80c8b2f0413"}]},{"id":2,"country":[{"id":"5a60626f1d41c80c8d3f8a83"},{"id":"5a60626f1d41c80c8d3f8a84"}]}]';
JSON.parse(json, (k, v) => v.big && ids.push(v));
console.log( ids );
I am not sure why noone mentioned flat() (probably for large arrays, it might be less performant)
(data || []).map(o=>{
return o.country.map(o2=>({id: o2.id}))
}).flat()
Related
I have this array of objects, within it I have another array of objects:
[
{
id: 1,
country: [
{
id: "5a60626f1d41c80c8d3f8a85"
},
{
id: "5a6062661d41c80c8b2f0413"
}
]
},
{
id: 2,
country: [
{
id: "5a60626f1d41c80c8d3f8a83"
},
{
id: "5a60626f1d41c80c8d3f8a84"
}
]
}
];
How to get flat array of country like this:
[
{ id: "5a60626f1d41c80c8d3f8a85" },
{ id: "5a6062661d41c80c8b2f0413" },
{ id: "5a60626f1d41c80c8d3f8a83" },
{ id: "5a60626f1d41c80c8d3f8a84" }
];
without using a forEach and a temp variable?
When I did:
(data || []).map(o=>{
return o.country.map(o2=>({id: o2.id}))
})
I got the same structure back.
Latest edit
All modern JS environments now support Array.prototype.flat and Array.prototype.flatMap
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.flatMap(
(elem) => elem.country
)
)
Old answer
No need for any ES6 magic, you can just reduce the array by concatenating inner country arrays.
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.reduce(
(arr, elem) => arr.concat(elem.country), []
)
)
If you want an ES6 feature (other than an arrow function), use array spread instead of the concat method:
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.reduce(
(arr, elem) => [...arr, ...elem.country], []
)
)
Note: These suggestions would create a new array on each iteration.
For efficiency, you have to sacrifice some elegance:
const data=[{id:1,country:[{id:"5a60626f1d41c80c8d3f8a85"},{id:"5a6062661d41c80c8b2f0413"}]},{id:2,country:[{id:"5a60626f1d41c80c8d3f8a83"},{id:"5a60626f1d41c80c8d3f8a84"}]}];
console.log(
data.reduce(
(arr, elem) => {
for (const c of elem.country) {
arr.push(c);
}
return arr;
}, []
)
)
const raw = [
{
id: 1,
country: [
{
id: "5a60626f1d41c80c8d3f8a85"
},
{
id: "5a6062661d41c80c8b2f0413"
}
]
},
{
id: 2,
country: [
{
id: "5a60626f1d41c80c8d3f8a83"
},
{
id: "5a60626f1d41c80c8d3f8a84"
}
]
}
];
const countryIds = raw
.map(x => x.country)
.reduce((acc, curr) => {
return [
...acc,
...curr.map(x => x.id)
];
}, []);
console.log(countryIds)
This, works, just concat the nested arrays returned by your solution
let arr = [{ "id": 1,
"country": [{
"id": "5a60626f1d41c80c8d3f8a85",
},
{
"id": "5a6062661d41c80c8b2f0413",
}
]
},
{
"id": 2,
"country": [{
"id": "5a60626f1d41c80c8d3f8a83",
},
{
"id": "5a60626f1d41c80c8d3f8a84",
}
]
}
];
//If you want an array of country objects
console.log([].concat.apply(...(arr || []).map(o=> o.country)))
//If you can an array od country ids
console.log([].concat.apply(...(arr || []).map(o=> o.country.map(country => country.id))))
Ayush Gupta's solution will work for this case. But I would like to provide other solution.
const arr = [
{
id: 1,
country: [
{
id: '5a60626f1d41c80c8d3f8a85'
},
{
id: '5a6062661d41c80c8b2f0413'
}
]
},
{
id: 2,
country: [
{
id: '5a60626f1d41c80c8d3f8a83'
},
{
id: '5a60626f1d41c80c8d3f8a84'
}
]
}
];
const ids = arr.reduce(
(acc, {country}) => [
...acc,
...country.map(({id}) => ({
id
}))
],
[]
);
console.log(ids);
For JSON string data, it can be done during parsing too :
var ids = [], json = '[{"id":1,"country":[{"id":"5a60626f1d41c80c8d3f8a85"},{"id":"5a6062661d41c80c8b2f0413"}]},{"id":2,"country":[{"id":"5a60626f1d41c80c8d3f8a83"},{"id":"5a60626f1d41c80c8d3f8a84"}]}]';
JSON.parse(json, (k, v) => v.big && ids.push(v));
console.log( ids );
I am not sure why noone mentioned flat() (probably for large arrays, it might be less performant)
(data || []).map(o=>{
return o.country.map(o2=>({id: o2.id}))
}).flat()
[
{“id”:”idtest1",”name”:”aaa"},
{“id”:”idlest2”,”name”:”bbb"},
{“id”:”idlest3","name”:"ccc"},
{“id”:”idtest4","name”:"ddd”},
… ]
I want to get only the name from these arrays. And I want to create a new array using name. The value of name becomes a key and adds a static string to the value.
The static value is increased by one. What should I do?
{
“aaa" : [
"static01value", "static01value", "static01value"
],
“bbb" : [
"static02value", "static02value", "static02value"
],
…..
}
let list = [
{"id":"idtest1","name":"aaa"},
{"id":"idlest2","name":"bbb"},
{"id":"idlest3","name":"ccc"},
{"id":"idtest4","name":"ddd"},
]
let result = list.reduce((acc, {name}, i) => {
acc[name] = Array.from({ length: 3 }, () => `static0${i}value`);
return acc;
}, {});
console.log(result)
You can use reduce method and use Array.from method which
take a length for the array and a callback function which you can use
to modify that array
This is the snippet of what the code should look like, given that the static value is a bit vague:
var array = [
{ id: "idtest1", name: "aaa" },
{ id: "idlest2", name: "bbb" },
{ id: "idlest3", name: "ccc" },
{ id: "idtest4", name: "ddd" }
];
var arrName = array.map(a => a.name),
newArray = [];
arrName.forEach((a, idx) => {
var newObject = {}
newObject[a] = [];
//not quite sure what your static value is, in your example you have 3 static value
for (var i = 0; i < 3; i++) {
newObject[a].push('static value' + idx);
}
newArray.push(newObject);
});
console.log(newArray);
Please try below.
var array = [
{ id: "idtest1", name: "aaa" },
{ id: "idlest2", name: "bbb" },
{ id: "idlest3", name: "ccc" },
{ id: "idtest4", name: "ddd" }
];
const result = {};
array.forEach((item, staticIndex) => {
const staticArray = []
// add static value to array
staticArray.push('staticValue');
result[item.name] = staticArray
})
console.log('Result array is ', result);
Just try to parse your Json using es6 methods.
const array = [
{ id: "idtest1", name: "aaa" },
{ id: "idlest2", name: "bbb" },
{ id: "idlest3", name: "ccc" },
{ id: "idtest4", name: "ddd" }
];
const your_static_content = 'your_static_content'
const output = array.reduce((obj, item) => {
obj[item.name] = obj[item.name] || [];
obj[item.name].push(your_static_content);
return obj;
}, Object.create(null));
console.log(output)
const data = [
{ "id": "idtest1", "name": "aaa" },
{ "id": "idtest2", "name": "bbb" },
{ "id": "idtest3", "name": "ccc" },
{ "id": "idtest4", "name": "ddd" }
]
const getStaticValue = index => `static0${1 + index}value`
const result = data.reduce((result, {name}, index) => ({
...result,
[name]: Array.from({length:3}, getStaticValue)
}), {})
console.log(result)
I have this,
var o = [{
"id": 1, // its actually a string in real life
"course": "name1",
// more properties
},
{
"id": 1, // its actually a string in real life
"course": "name2",
// more properties
}];
I want this,
var r = [{
"id": 1, // its actually a string in real life
"course": ["name1", "name2"],
}];
I am trying this,
var flattened = [];
for (var i = 0; i < a.length; ++i) {
var current = a[i];
if(flattened.)
}
but I am stuck, I am not sure what to do next, array will have more then 2 records but this was just an example.
THERE are more fields but I removed them for simplicity, I won't be using them in final array.
You could reduce the array and find the object.
var array = [{ id: 1, course: "name1" }, { id: 1, course: "name2" }],
flat = array.reduce((r, { id, course }) => {
var temp = r.find(o => id === o.id);
if (!temp) {
r.push(temp = { id, course: [] });
}
temp.course.push(course);
return r;
}, []);
console.log(flat);
The same by taking a Map.
var array = [{ id: 1, course: "name1" }, { id: 1, course: "name2" }],
flat = Array.from(
array.reduce((m, { id, course }) => m.set(id, [...(m.get(id) || []) , course]), new Map),
([id, course]) => ({ id, course })
);
console.log(flat);
This way you will get the data flattened in the shape you want
const o = [
{
id: 1,
course: "name1"
},
{
id: 1,
course: "name2"
},
{
id: 2,
course: "name2"
}
];
const r = o.reduce((acc, current) => {
const index = acc.findIndex(x => x.id === current.id);
if (index !== -1) {
acc[index].course.push(current.course);
} else {
acc.push({id:current.id, course: [current.course]});
}
return acc
}, []);
console.log(r);
You can do this with reduce and Object.entries. This example works for any number of properties:
const o = [
{ id: 1, course: 'name1', time: 'morning', topic: 'math' },
{ id: 1, course: 'name2', time: 'afternoon' },
{ id: 2, course: 'name3', time: 'evening' }
];
const result = o.reduce((out, { id, ...rest }) => {
out[id] = out[id] || {};
const mergedProps = Object.entries(rest).reduce((acc, [k, v]) => {
return { ...acc, [k]: [...(out[id][k] || []), v] };
}, out[id]);
out[id] = { id, ...mergedProps };
return out;
}, {});
console.log(result);
If you only care about the id and course fields, you can simplify to this:
const o = [
{ id: 1, course: 'name1', time: 'morning', topic: 'math' },
{ id: 1, course: 'name2', time: 'afternoon' },
{ id: 2, course: 'name3', time: 'evening' }
];
const result = o.reduce((out, { id, course }) =>
({ ...out, [id]: { id, course: [...((out[id] || {}).course || []), course] } })
, {});
console.log(result);
You could use .reduce to create an object of keys, and then use that object to set keys to be of the id. This way you can add to the same course array by targetting the id of the object. Lastly, you can get the values of the object to get your result.
See example below:
var o = [{
"id": 1,
"course": "name1",
"foo": 1
},
{
"id": 1,
"course": "name2",
"bar": 2
}];
var res = Object.values(o.reduce((acc, {id, course, ...rest}) => {
if(id in acc)
acc[id] = {...acc[id], course: [...acc[id].course, course], ...rest};
else acc[id] = {id, course: [course], ...rest};
return acc;
}, {}));
console.log(res);
function merge(array, key = 'id') {
const obj = {}
for(const item of array) {
const existing = obj[item[key]]
if(existing) {
for(const [name, value] of Object.entries(item)) {
if(name === key) continue;
if(existing[name]) {
existing[name] = [ ...(existing[name].$custom ? existing[name] : [existing[name]]), value ]
existing[name].$custom = true;
} else {
existing[name] = value;
}
}
} else {
obj[item[key]] = { ...item }
}
}
return Object.values(obj)
}
var o = [
{
"id": 1,
"single": "test"
},
{
"id": 1,
"course": "name1",
"multifield": "test"
},
{
"id": 1,
"course": "name2"
},
{
"id": 1,
"newfield": "test"
}, {
"id": 2,
"anotherid": "test",
"array": [1,3,4]
}, {
"id": 2,
"array": "text"
}];
console.log(merge(o))
You can use reduce to accumulate the results. Search in the current result (accumulator a) for an object (el) with the same id, if found, append course to existing object and return the same accumulator, otherwise put into the accumulator with course as an array.
var res = o.reduce((a, {id,course}) => {
var found = a.find(el => el.id == id);
return found ? found.course.push(course) && a : [...a, {id, course: [course]}];
}, []);
My code has an array of elements as follows:
element: { fromX: { id: ... } , toX: { id: ... } }
Requirement is to pull all the fromX ids into one array, and all toX ids into other.
There are a couple of different ways,
such as using foreach, reduce, iterating for each respectively, but I'm searching for an optimal functional way to return two arrays with one mapping?
Using Array#reduce and destructuring
const data=[{fromX:{id:1},toX:{id:2}},{fromX:{id:3},toX:{id:4}},{fromX:{id:5},toX:{id:6}},{fromX:{id:7},toX:{id:8}}]
const [fromX,toX] = data.reduce(([a,b], {fromX,toX})=>{
a.push(fromX.id);
b.push(toX.id);
return [a,b];
}, [[],[]]);
console.log(fromX);
console.log(toX);
You could take an array for the wanted keys and map the value. Later take a destructuring assignment for getting single id.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
array = [{ fromX: { id: 1 }, toX: { id: 2 } }, { fromX: { id: 3 }, toX: { id: 4 } }],
keys = ['fromX', 'toX'],
[fromX, toX] = transpose(array.map(o => keys.map(k => o[k].id)));
console.log(fromX);
console.log(toX);
Try this:
const arr = [{
fromX: {
id: 1
},
toX: {
id: 2
}
}, {
fromX: {
id: 3
},
toX: {
id: 4
}
}]
let {
arr1,
arr2
} = arr.reduce((acc, {
fromX,
toX
}) => ({ ...acc,
arr1: [...acc.arr1, fromX],
arr2: [...acc.arr2, toX]
}), {
arr1: [],
arr2: []
})
console.log(arr1, arr2);
You can achieve this by using below solution
var array = [{ fromX: { id: 1 }, toX: { id: 2 } }, { fromX: { id: 3 }, toX: { id: 4 } }],
arrayX = array.map(x => x.fromX), arraytoX = array.map(toX => toX.toX)
console.log(arrayX);
console.log(arraytoX );
I have two arraysmetaObjects and justObjects.
These Objects in both arrays have the id property in common.
I would like to create a new array that combines properties from the objects in the different arrays
const metaObjects = [
{
id: 1,
metaProp: "metaProp1"
},
{
id: 2,
metaProp: "metaProp2"
}
];
const justObjects = [
{
id: 1,
justProp: "justProp1"
},
{
id: 2,
justProp: "justProp2"
}
];
This is the outcome I expect
const result= [
{
id: 1,
metaProp: "metaProp1",
justProp: "justProp1"
},
{
id: 2,
metaProp: "metaProp2",
justProp: "justProp2"
}
];
I have tried to implement map of map to achieve this
const combinedObject = justObjects.map(_w => {
return metaObjects.map(_m => {
if (_w.id === _m.id) {
return { ..._m, ..._w };
}
});
}, metaObjects);
console.log(combinedObject);
But I get the following error
[ [ { id: 1, metaProp: 'metaProp1', justProp: 'justProp1' },
undefined ],
[ undefined,
{ id: 2, metaProp: 'metaProp2', justProp: 'justProp2' } ] ]
I am not sure why each array has an undefined in the inner arrays.
Also I need to flatten the arrays so that they are close to the expected results above.
I have heard about the composable lens functions of ramda
Could that be used here?
This is fairly similar to the answer from customcommander, but chooses to use groupBy and values rather than sortBy and groupWith. This feels more logical to me, especially avoiding an unnecessary sort call.
const {pipe, concat, groupBy, prop, values, map, mergeAll} = R
const joinOnId = pipe
( concat
, groupBy (prop ('id'))
, values
, map (mergeAll)
)
const metaObjects =
[ { id: 1, metaProp: "metaProp1" }
, { id: 2, metaProp: "metaProp2" }
, { id: 3, metaProp: "metaProp3" } // unique to `meta`
]
const justObjects =
[ { id: 1, justProp: "justProp1" }
, { id: 2, justProp: "justProp2" }
, { id: 4, justProp: "justProp4" } // unique to `just`
]
console.log
( joinOnId (metaObjects, justObjects)
)
.as-console-wrapper {
max-height: 100vh !important;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
Note that this can easily be adjusted to accept different property name:
const joinOn = (propName) =>
pipe
( concat
, groupBy (prop (propName))
, values
, map (mergeAll)
)
// ...
const joinOnId = joinOn ('id')
or to use any common key-generation function:
const joinOn = (keyFn) =>
pipe
( concat
, groupBy (keyFn)
, values
, map (mergeAll)
)
// ...
const joinOnId = joinOn (prop ('id'))
You can search for the object to merge with find() and then use Object.assign() to merge them together. This assumes that the object already exists in metaObjects, if it doesn't you'll need to decide what to do in that case.
const metaObjects = [
{
id: 1,
metaProp: "metaProp1"
},
{
id: 2,
metaProp: "metaProp2"
}
];
const justObjects = [
{
id: 1,
justProp: "justProp1"
},
{
id: 2,
justProp: "justProp2"
}
];
justObjects.forEach(item => {
let toMerge = metaObjects.find(obj => obj.id === item.id)
Object.assign(toMerge, item)
})
console.log(metaObjects)
If metaObjects is potentially large, it would be better to store it as an object keyed to id. Then you could look it up directly without having to search each time.
If you don't want to alter metaObjects, you can map() over justObjects and create a new array:
const metaObjects = [
{
id: 1,
metaProp: "metaProp1"
},
{
id: 2,
metaProp: "metaProp2"
}
];
const justObjects = [
{
id: 1,
justProp: "justProp1"
},
{
id: 2,
justProp: "justProp2"
}
];
let newArray = justObjects.map(item => {
let toMerge = metaObjects.find(obj => obj.id === item.id)
return Object.assign({}, toMerge, item)
})
// metaObjects unaffected
console.log(newArray)
I think you could simply combine the two arrays together, group objects by id (you need to sort first) and finally merge each group:
const {
map,
mergeAll,
groupWith,
eqBy,
prop,
concat,
sortBy,
pipe
} = R;
const metaObjects = [
{ id: 1,
metaProp: "metaProp1" },
{ id: 2,
metaProp: "metaProp2" }];
const justObjects = [
{ id: 1,
justProp: "justProp1" },
{ id: 2,
justProp: "justProp2" }];
const process = pipe(
concat,
sortBy(prop('id')),
groupWith(eqBy(prop('id'))),
map(mergeAll));
console.log(
process(metaObjects, justObjects)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
I would use Array.prototype.reduce() or a for loop to convert one of them from an Array of objects with an id property to an object of objects, using the id as the key:
const merged = metaObjects.reduce((acc, cur) => {
acc[cur.id] = cur;
return acc;
}, {});
Or:
const merged = {};
for (const obj of metaObjects) {
merged[obj.id] = obj;
}
Then, iterate the other one while merging each of its entries in the object we have just created above:
justObjects.forEach((obj) => {
merged[obj.id] = Object.assign({}, merged[obj.id], obj);
});
Lastly, just convert it back to an Array using Object.values:
Object.values(merged);
Example:
const metaObjects = [{
id: 1,
metaProp: "metaProp1"
},{
id: 2,
metaProp: "metaProp2"
}];
const justObjects = [{
id: 1,
justProp: "justProp1"
},{
id: 2,
justProp: "justProp2"
},{
id: 3,
justProp: "justProp3"
}];
// Create an object of one of the two using is id property:
/*
// Alternative using reduce:
const merged = metaObjects.reduce((acc, cur) => {
acc[cur.id] = cur;
return acc;
}, {});
*/
// Alternative using a for loop:
const merged = {};
for (const obj of metaObjects) {
merged[obj.id] = obj;
}
// Iterate the other one and merge it with the map you have just created:
justObjects.forEach((obj) => {
merged[obj.id] = Object.assign({}, merged[obj.id], obj);
});
// Convert it back to an Array of objects:
console.log(Object.values(merged));
.as-console-wrapper {
max-height: 100vh !important;
}
Note this will work even if any of the two objects contain entries for an id that is not present in the other.