Javascript 从对象中删除除指定键之外的所有元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36579679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all elements from object except specified key?
提问by panthro
I have an object:
我有一个对象:
"languages": {
"en":["au", "uk"],
"de":["de"],
....
}
How can I remove everything but a specified key, so if I specify 'en' I just want an object that contains "en":["au", "uk"]
如何删除除指定键之外的所有内容,所以如果我指定“en”,我只想要一个包含“en”的对象:[“au”,“uk”]
回答by isvforall
Simply, you could create a new object with specified field;
简单地说,您可以创建一个具有指定字段的新对象;
var key = 'en';
var o = {
"languages": {
"en": ["au", "uk"],
"de": ["de"]
}
}
var res = {}
res[key] = o.languages[key];
回答by Dave
General solution for the original question of 'how do I remove all keys except specified keys' (refined from Rajaprabhu's answer):
原始问题“如何删除指定键之外的所有键”的通用解决方案(从 Rajaprabhu 的回答中提炼出来):
validKeys = [ 'a', 'b', 'c' ];
userInput = { "a":1, "b":2, "c":3, "d":4, "e":5 }
Object.keys(userInput).forEach((key) => validKeys.includes(key) || delete userInput[key]);
回答by Rajaprabhu Aravindasamy
回答by Barmar
A simple loop using delete
will do it.
一个简单的循环delete
就可以做到。
var key = 'en';
for (var k in obj.languages) {
if (obj.languages.hasOwnProperty(k) && k != key) {
delete obj.languages[k];
}
}
回答by Quentin C
Was searching for the answer and the previous ones helped me, just adding a functional version of the codethat I needed:
正在寻找答案,以前的答案对我有帮助,只是添加了我需要的代码的功能版本:
function returnNewObjectOnlyValidKeys(obj, validKeys) {
const newObject = {};
Object.keys(obj).forEach(key => {
if (validKeys.includes(key)) newObject[key] = obj[key];
});
return newObject;
}