[通过JavaScript中的字符串数组从对象中提取键和值

问题描述 投票:-1回答:2

我有一些作为对象返回的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"
}
javascript arrays object destructuring
2个回答
0
投票

您可以使用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);

0
投票

您可以遍历数组:

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))
© www.soinside.com 2019 - 2024. All rights reserved.