I would like to copy an array so as not to modify the original, and remove all selected: false from new array, and return this new array. The array is infinitely nested, and with infinite property names non of which are predictable, so this should be possible through iteration looking at the value of each property for Array.isArray(). While I can remove selected:false objects in the iteration, I fail to return the modified array back to the new array.
function failing to filter aliens. Also, function works in CodePen, but not in my code.
// sample nested data
var data = [
{
partyId: "animal-ID-001",
selected: false,
members: [
{
selected: false,
userId: "animal-user-3443"
},
{
selected: false,
userId: "animal-user-3444"
}
]
},
{
partyId: "benjamin-ID-002",
selected: true,
members: [
{
selected: true,
userId: "benjamin-user-5567",
teams: [
{
selected: true,
teamId: "team-benjamin-678"
},
{
selected: false,
teamId: "team-benjamin-3468"
}
]},
{
selected: false,
userId: "benjamin-user-55671"
}
]
},
{
partyId: "crystal-ID-003",
selected: true,
members: [
{
selected: true,
userId: "crystal-user-8567"
},
{
selected: true,
userId: "crystal-user-85671"
}
],
aliens: [
{
selected: false,
alienId: "crystal-alien-467"
},
{
selected: false,
alienId: "crystal-alien-230"
}
]
}
];
// remove selected false from array
// updated per suggestions
function updateState(arr) {
return arr.filter(obj => obj.selected ).map( obj => {
for (var prop in obj) {
if( Array.isArray( obj[prop] ) ) {
return { ...obj, [prop]: updateState( obj[prop] ) };
}
}
return { ...obj }
});
}
console.log( updateState( data ) );
updateState( obj[prop] )do?var arr = [...originalArr];is a shallow copy. Uselodashit hasdeepClonefunction but if you insist on not using an external library you can also do:arr = JSON.parse(JSON.stringify(data))but make sure to read this first: medium.com/@pmzubar/…