我有一些作为对象返回的api数据:
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male"
}
我有一个配置列表中的键列表,我有兴趣从原始响应中提取这些键:
let attributes = ['name', 'height', 'mass'];
我如何使用属性数组像这样给我一个对象:
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77"
}
您可以使用Object.entries
方法。
let obj = {"name": "Luke Skywalker","height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair","eye_color": "blue","birth_year": "19BBY", "gender": "male"};
let attributes = ['name', 'height', 'mass'];
let picked = Object.fromEntries(
Object.entries(obj)
.filter(([key]) => attributes.includes(key))
)
console.log(picked);
您可以遍历数组:
const obj = {
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male"
};
let attributes = ['name', 'height', 'mass'];
function buildObject(arr, obj) {
const res = {};
arr.forEach(item => res[item] = obj[item])
return res
}
console.log(buildObject(attributes, obj))