I have an array of objects as follows
const array = [
{id:1,parentIds:[]}
{id:2,parentIds:[1,3]}
{id:3,parentIds:[1,2,4]}
]
How can I make it possible to remove an object's parentIds value if it doesn't exist in the array? to look something like this
const array = [
{id:1,parentIds:[]}
{id:2,parentIds:[1,3]}
{id:3,parentIds:[1,2]}
]
You can try this solution:
const array = [{
id: 1,
parentIds: []
}, {
id: 2,
parentIds: [1, 3]
}, {
id: 3,
parentIds: [1, 2, 4]
}];
const idsArr = new Set(array.map(el => el.id));
array.forEach(el => {
el.parentIds = el.parentIds.filter(el => idsArr.has(el));
})
console.log(array);
It's better to avoid mutating the original array parentIds, use immutation to create new array:
const array = [
{id:1,parentIds:[]},
{id:2,parentIds:[1,3]},
{id:3,parentIds:[1,2,4]}
]
const ids = array.map(({id}) => id)
const newArray = array.map(({parentIds,...arrayItemRest}) => {
const newparentIds = parentIds.filter(id => ids.includes(id))
return {
...arrayItemRest,
parentIds: newparentIds
}
})
const array = [
{id:1,parentIds:[]},
{id:2,parentIds:[1,3]},
{id:3,parentIds:[1,2,4]}
]
// Let's create an array only containing the ids
var ids = array.map(o => o.id)
// Loop array
array.forEach((object) => {
// Loop all parent ids
object.parentIds.forEach((id, index) => {
// Check if we find the id in our list
if (ids.indexOf(id) === -1) {
// Delete item from array if not found
object.parentIds.splice(index, 1)
}
})
})
// The result
console.log(array)