Can I merge 2 arrays with the same value of the same key? Already tried using map.set() but it wont work on my end.
const errArray = [
{ 'id': 1, 'error': ["Error 1", "Error2"] }
{ 'id': 2, 'error': ["Error 3", "Error4"] }
]
const warnArray = [
{ 'id': 1, 'warning': ["Error 5", "Error6"]}
]
I want to have a result of :
[
{ 'id': 1,
'error': ["Error 1", "Error2"],
'warning': ["Error 5", "Error6"]
}, {
'id': 2,
'error': ["Error 3", "Error4]
}
]
CodePudding user response:
You first concat
them into one array. Then group by id
, extending into each other those who match by id
.
Then finally flatten the object into array.
const errArray = [{
'id': 1,
'error': ["Error 1", "Error2"]
},
{
'id': 2,
'error': ["Error 3", "Error4"]
}
]
const warnArray = [{
'id': 1,
'warning': ["Error 5", "Error6"]
}]
var combined = errArray.concat(warnArray)
var result = Object.values(combined.reduce(function(agg, value) {
agg[value.id] = Object.assign({}, value, agg[value.id]);
return agg;
}, {}));
console.log(result)
CodePudding user response:
const errArray = [
{ 'id': 1, 'error': ["Error 1", "Error2"] },
{ 'id': 2, 'error': ["Error 3", "Error4"] }]
const warnArray = [
{ 'id': 1, 'warning': ["Error 5", "Error6"]},
{ 'id': 2, 'warning': ["Error 5", "Error6"]},
{ 'id': 3, 'warning': ["Error 5", "Error6"]}
]
let merged = []
if(errArray.length > warnArray.length){
merged = errArray.map((item, i) => Object.assign({}, item, warnArray[i]));
}
else{
merged = warnArray.map((item, i) => Object.assign({}, item, errArray[i]));
}
console.log(merged);
CodePudding user response:
Here is the implementation using the map:
const errArray = [
{ 'id': 1, 'error': ["Error 1", "Error2"] },
{ 'id': 2, 'error': ["Error 3", "Error4"] }
]
const warnArray = [
{ 'id': 1, 'warning': ["Error 5", "Error6"]}
]
const myMap = new Map();
errArray.forEach(err => {
myMap.set(err.id, err);
});
warnArray.forEach(warn => {
if(!myMap.has(warn.id)) {
myMap.set(warn.id, warn);
}
else {
// You might want to do better merging than this, if the objects are complex
const mergedObj = Object.assign({}, myMap.get(warn.id), warn);
myMap.set(warn.id, mergedObj)
}
});
const resultArr = Array.from(myMap.values());
console.log(resultArr)
CodePudding user response:
You can make an array of unique id
by mapping each array to its id
and creating a spread Set
of them with [...new Set(Array)]
. Then you can map
each key to a combined object with Object.assign()
and array.find()
:
const errArray = [
{ 'id': 1, 'error': ["Error 1", "Error2"] },
{ 'id': 2, 'error': ["Error 3", "Error4"] }
]
const warnArray = [
{ 'id': 1, 'warning': ["Error 5", "Error6"]}
]
const keys = [
...new Set([
...errArray.map((v) => v.id), // [1, 2]
...warnArray.map((v) => v.id) // [1]
]),
]; // keys = [1, 2]
const combined = keys.map((key) =>
Object.assign({},
errArray.find((v) => v.id === key),
warnArray.find((v) => v.id === key)
)
);
console.log(combined)