How Remove Excess Property From Object By Condition?
I have two object. I first object is an object which contains elements from second object. But in first objects contains such elements which are absent in the seconds object. I nee
Solution 1:
You could take a function for filtering the nested array and hand over the array and a Set
with the wanted id
, which are kept in the result set.
In the function reduce the array by separating children
from the object and filter the children.
If the id
of the item is in the set or the children have some items push the object to the result set by checking the children as well.
functionfilter(array, ids) {
return array.reduce((r, { children = [], ...o }) => {
children = filter(children, ids);
if (ids.has(o.id) || children.length) r.push(Object.assign(o, children.length && { children }));
return r;
}, []);
}
var data = [{ text: "A", children: [{ text: "B", children: [{ text: "C", children: [{ text: "B [43]", id: "43" }, { text: "B [11]", id: "11" }, { text: "B [93]", id: "93" }] }] }] }, { text: "W", children: [{ text: "M", children: [{ text: "K", children: [{ text: "M [48]", id: "48" }, { text: "M [58]", id: "58" }] }] }, { text: "T", children: [{ text: "K", children: [{ text: "S [78]", id: "78" }] }] }] }, { text: "D", children: [{ text: "M", children: [{ text: "N", children: [{ text: "M [66]", id: "66" }] }] }] }, { text: "Q", children: [{ text: "Y", children: [{ text: "N", children: [{ text: "I [15]", id: "15" }, { text: "I [13]", id: "13" }] }] }] }],
keep = [{ id: "43", text: "B [43]" }, { id: "93", text: "B [93]" }, { id: "66", text: "B [66]" }, { id: "13", text: "I [13]" }],
result = filter(data, newSet(keep.map(({ id }) => id)));
console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Post a Comment for "How Remove Excess Property From Object By Condition?"