How can I filter arrayObjects
to return ["test1", "test2", "test3"]
const arrayObjects = [{
date: "2021-02-17",
someAction: [{
id: "1",
metatags: {
addedBy: "test1"
}
}, {
id: "2",
metatags: {
addedBy: "test2"
}
}]
}, {
date: "2021-02-16",
someAction: [{
id: "3",
metatags: {
addedBy: "test1"
}
}]
}, {
date: "2021-02-15",
someAction: [{
id: "4",
metatags: {
addedBy: "test3"
}
}, {
id: "5",
metatags: {
addedBy: "test2"
}
}]
}]
I`m writing something like this:
arrayObjects?.map(arr => arr.someAction.map(a=> a.metatags.addedBy))
Not sure I understand completely, but this snippet will create a new array containing the addedBy data for each action nested in the parent object.
what you need to use is
reduce
which will help you to create the desired output.Firsly you need to flat the result and then pick unique items.
To flat an array you can use
flat
array method, and for gathering unique results I’d suggest you to use Set data structure (by definition it has only unique items) and the cast to array usingArray.from
Probably, looks pretty complex, but works as a charm 🙂
May ways to attack it. I would use Object.keys, reduce with and object, and forEach
If you want to go the map() route. You would need to use two maps, flat, and a set to get them deduped