I have a nested object of this structure.
mainObject: {
1: {
id: 1,
name:'alpha'
},
2: {
id: 2,
name:'beta'
},
3: {
id: 3,
name:'gamma'
}
}
i want to delete on object from this ,say 1 but that in an immutable way . I tried the following code.
const list =Object.values(mainObject)
const newList=list.filter((item)=>{item.id!=1})
newList.forEach((item)=>{
mainObject[item.id]={
id: item.id,
name:item.name
}
})
this is not working .What am i doing wrong. Thanks in advance.
2 Answers 2
You could use destruct assignment for deletion
const { 1: _, ...newObject } = mainObject
const mainObject = {
1: {
id: 1,
name: "alpha",
},
2: {
id: 2,
name: "beta",
},
3: {
id: 3,
name: "gamma",
},
}
const { 1: _, ...newObject } = mainObject
console.log(mainObject)
console.log(newObject)
Or clone mainObject in to an different object then apply deletion
const newObject = { ...mainObject }
delete newObject[1]
const mainObject = {
1: {
id: 1,
name: "alpha",
},
2: {
id: 2,
name: "beta",
},
3: {
id: 3,
name: "gamma",
},
}
const newObject = { ...mainObject }
delete newObject[1]
console.log(mainObject)
console.log(newObject)
Or transform object into array of key-value pairs, reject your delete pair and then transform it back to object
const newObject = Object.fromEntries(
Object.entries(mainObject).filter(([key]) => key !== "1")
)
const mainObject = {
1: {
id: 1,
name: "alpha",
},
2: {
id: 2,
name: "beta",
},
3: {
id: 3,
name: "gamma",
},
}
const newObject = Object.fromEntries(
Object.entries(mainObject).filter(([key]) => key !== "1")
)
console.log(mainObject)
console.log(newObject)
Reference
4 Comments
newObject is a shallow copykey !== "1"?You can use delete operator and spread syntax to achieve what you want.
For the object you have mentioned, let me walk you through it.
const mainObject = {
1: {
id: 1,
name: 'alpha',
},
2: {
id: 2,
name: 'beta',
},
3: {
id: 3,
name: 'gamma',
},
};
const newObj = { ...mainObject};
delete newObj["1"];
Read More on Spread syntax on MDN
Read More on delete operator on MDN
Hope it helps🙂
const mainObject = {
1: {
id: 1,
name: 'alpha',
},
2: {
id: 2,
name: 'beta',
},
3: {
id: 3,
name: 'gamma',
},
};
const newObj = { ...mainObject};
delete newObj["1"];
document.write(`<p>mainObject:</p> <pre> ${JSON.stringify(mainObject)} </pre>`)
document.write(`<p>newObj:</p> <pre> ${JSON.stringify(newObj)} </pre>`)
delete mainObject[1]doesn't work?const newList=list.filter((item)=>{item.id!=1})will ALWAYS be an empty list since your callback doesn't return anything