'Node JS - Parse object where keys are arrays of objects using those objects properties as conditions
I have an Object where each key is an Actor name and its property is an array of objects with some infos, like below:
const x = {
'Jonathan Majors': [
{
character: 'Kang the Conqueror',
title: 'Ant-Man and the Wasp: Quantumania',
release_date: '2023-07-26'
},
{
character: 'He Who Remains (archive footage)',
title: "Marvel Studios' 2021 Disney+ Day Special",
release_date: '2021-11-12'
}
],
'Vin Diesel': [
{
character: 'Groot (voice)',
title: 'Guardians of the Galaxy Vol. 3',
release_date: '2023-05-03'
},
{
character: 'Self',
title: 'Marvel Studios: Assembling a Universe',
release_date: '2014-03-18'
}
]
}
The condition to the new object is to return only the Actors that have more than one character, excluding the character Self .. so if the Actor has two chars, but one is self, it should be deleted
const result = {
'Jonathan Majors': [
{
character: 'Kang the Conqueror',
title: 'Ant-Man and the Wasp: Quantumania',
release_date: '2023-07-26'
},
{
character: 'He Who Remains (archive footage)',
title: "Marvel Studios' 2021 Disney+ Day Special",
release_date: '2021-11-12'
}
]
}
Solution 1:[1]
You can use a combination of Object.entries, Object.fromEntries, filter functions and a set.
const result = Object.fromEntries(
Object.entries(x)
.filter(([,data]) =>
new Set(data.filter(({character}) => character !== 'Self')).size > 1
)
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jkoch |
