简体   繁体   中英

How to remove object from object of objects in javascript

I have an object as follows:

let object = {
   1: {id: 1, name: "One"},
   2: {id: 2, name: "Two"},
   3: {id: 3, name: "Three"}
}

And I want to remove one of them, for example the object with id 2

Now I do it using lodash as follows:

forOwn(object, function(value, key) {
     value.id === 2 && delete object[key]
});

That does the trick but is it the right way?

You can use UnderscoreJs Library

let object = {
   1: {id: 1, name: "One"},
   2: {id: 2, name: "Two"},
   3: {id: 3, name: "Three"}
}

let newobject=_.remove(object,function(nv){
return nv.id===3;
});

the above code will delete the object having id=3 and return

{
  1: {id: 1, name: "One"},
  2: {id: 2, name: "Two"},
}

I think you're not getting the answers you're looking for, because maybe you've over simplified the use-case, so it's tempting to just say:

delete object[2]; // which modifies the original object

If your data is not that static, or if you want to do something more complex to remove certain elements, you could do something similar to this:

const relevantObjects = Object.entries(object) // converts each entry to [key, value]
  .filter(([k, v]) => v.id !== 2) // define the criteria to include/exclude items
  .reduce((acc, [k, v]) => {
    acc[k] = v;
    return acc; // this function can be improved, it converts the [[k, v]] back to {k: v, k: v, ...}
  }, {});

Edit:

It's perfectly fine to use a lib or whatever. Everything has its pros & cons, just do whatever works for you <3

I would use a simple for ... in instead of loadash

 let object = { 1: {id: 1, name: "One"}, 2: {id: 2, name: "Two"}, 3: {id: 3, name: "Three"} } let deleteById = (obj,idToRemove) => { for(let key in obj){ let {id} = obj[key] | {} if(id === idToRemove){ delete obj[key] } } } deleteById(object,2) console.log(object)

This is the right way. To do it in JSON you do the following:

var json = { ... };
var key = "foo";
delete json[key];

So if you swap out json to object you are all set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM