说我们有一个像这样的对象:
let obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"}
及其一些键的数组:
let arr_of_keys = ["a", "d", "e"]
是否可以使用数组中的预定义键来破坏对象,类似于以下内容:
let {...arr_of_keys} = obj;
最终以:
a =“约翰”,d =“约瑟夫”,e =“罗杰”
答案 0 :(得分:1)
您想要一种简单的.reduce
方法,如下所示:
var result = arr_of_keys.reduce(function(o,item){
if(obj.hasOwnProperty(item)){
o[item] = obj[item];
}
return o;
}, {});
这是一个例子:
let obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"}
let arr_of_keys = ["a", "d", "e", "f"];
var result = arr_of_keys.reduce(function(o,item){
if(obj.hasOwnProperty(item)){
o[item] = obj[item];
}
return o;
}, {});
console.log(result)
这是一个JSFiddle可运行的文件(因为内置的文件会返回503。)
答案 1 :(得分:1)
以下是所提供问题的可能的辅助功能。我添加了一个集合转换,以消除可能的重复,以节省资源。还以控制台错误消息的形式添加了简单的错误处理。
const obj = {a: "John", b: "Sarah", c: "Lara", d: "Joseph", e: "Roger"}
const arr_of_keys = ["a", "d", "e"];
const customObjectDescructurer = (arrayOfDesiredPropKeys, object) => {
const setOfDesiredPropKeys = new Set(arrayOfDesiredPropKeys);
const filteredObject = [...setOfDesiredPropKeys].reduce(
(filteredObject, desiredPropKey) => {
if(object.hasOwnProperty(desiredPropKey)){
filteredObject[desiredPropKey] = object[desiredPropKey];
} else {
console.error(`
The given ${desiredPropKey}, does not exist in ${object} object.
`);
}
return filteredObject;
}, {});
return filteredObject;
}
const desiredKeys = customObjectDescructurer(arr_of_keys, obj);
console.log(desiredKeys);