[英]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
我想删除其中之一,例如
id 2
的对象
Now I do it using lodash as follows:现在我使用 lodash 来做到这一点,如下所示:
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您可以使用UnderscoreJs库
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上面的代码将删除 id=3 的对象并返回
{
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.使用 lib 或其他东西完全没问题。 Everything has its pros & cons, just do whatever works for you <3
凡事有利有弊,做适合自己的事情<3
I would use a simple for ... in
instead of loadash
我会使用一个简单的
for ... in
而不是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:
要在 JSON 中执行此操作,请执行以下操作:
var json = { ... };
var key = "foo";
delete json[key];
So if you swap out json to object you are all set.因此,如果您将 json 换成 object,则一切就绪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.