仅保留JavaScript对象中的某些属性 [英] Keeping only certain properties in a JavaScript object
本文介绍了仅保留JavaScript对象中的某些属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象。我想通过删除除某些特定属性之外的所有属性来修改对象(而不是克隆它)。例如,如果我开始使用此对象:
I have an object. I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this object:
var myObj={
p1:123,
p2:321,
p3:{p3_1:1231,p3_2:342},
p4:'23423',
//....
p99:{p99_1:'sadf',p99_2:234},
p100:3434
}
和只想要属性p1,p2和p100,我该如何获得这个对象:
and only want properties p1, p2, and p100, how can I obtain this object:
var myObj={
p1:123,
p2:321,
p100:3434
}
我理解如何用蛮力做到这一点,但想要更优雅的解决方案。
I understand how I could do this with brute force, but would like a more elegant solution.
推荐答案
重新初始化对象:
myObj = {
p1: myObj.p1,
p2: myObj.p2,
p100: myObj.p100
};
另一种方法是删除某些效果较差的属性:
Another way is to delete certain properties, which is less effective:
var prop = ['p1', 'p2', 'p100'];
for (var k in myObj) {
if (prop.indexOf(k) < 0) {
delete myObj[k];
}
}
这篇关于仅保留JavaScript对象中的某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文