I have an array of objects, each containing arrays and I want to merge them if each array contains display: true
.
I'm very new to array manipulation, and a nudge in the correct way would be very much appreciated.
Example array:
{
"first": [
{
"name": "John",
"surname": "Doe",
"display": true
},
{
"name": "Jane",
"surname": "Doe",
"display": false
}
],
"second": [
{
"name": "Sarah",
"surname": "Doe",
"display": true
}
]
}
Example of expected result:
[
{
"name": "John",
"surname": "Doe",
"display": true
},
{
"name": "Sarah",
"surname": "Doe",
"display": true
}
]
I already have javascript code to set each display
key to true/false based on search query.
I just need the array merged to match the expected result.
CodePudding user response:
You could get all values and filter the flat array.
const
data = { first: [{ name: "John", surname: "Doe", display: true }, { name: "Jane", surname: "Doe", display: false }], second: [{ name: "Sarah", surname: "Doe", display: true }] },
result = Object
.values(data)
.flat()
.filter(({ display }) => display);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
Use a reducer and filter the values within on the display
property value. Finally flatten the result:
const mergedByDisplay = Object.entries({
"first": [{
"name": "John",
"surname": "Doe",
"display": true
},
{
"name": "Jane",
"surname": "Doe",
"display": false
}
],
"second": [{
"name": "Sarah",
"surname": "Doe",
"display": true
}]
}).reduce((acc, [key, val]) => [...acc, val.filter(v => v.display)], []);
console.log(mergedByDisplay.flat());
.as-console-wrapper { max-height: 100% !important; top: 0; }