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

时间:2020-02-06 15:36:16

标签: javascript arrays object destructuring

我有一些作为对象返回的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"
}

5 个答案:

答案 0 :(得分:3)

您可以遍历数组:

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))

答案 1 :(得分:3)

使用reduce将会得到简化。

const update = (data, attrs) =>
  attrs.reduce((acc, attr) => (acc[attr] = data[attr], acc), {});

const data = {
  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"];

console.log(update(data, attributes));

答案 2 :(得分:2)

您可以使用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(
  attributes.map(att => [att, obj[att]])
)
console.log(picked);

答案 3 :(得分:2)

您可以使用函数reduce来构建所需的对象。

let obj = {"name": "Luke Skywalker","height": "172","mass": "77","hair_color": "blond","skin_color": "fair","eye_color": "blue","birth_year": "19BBY","gender": "male"},
    attributes = ['name', 'height', 'mass'],
    {result} = attributes.reduce((a, c) => (Object.assign(a.result, {[c]: a.source[c]}), a), {result: Object.create(null), source: obj});
    
console.log(result);

答案 4 :(得分:2)

您可以映射所需的键及其值,并使用Object.fromEntries从中构建一个新对象。

let obj = { name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", eye_color: "blue", birth_year: "19BBY", gender: "male" },
    attributes = ['name', 'height', 'mass'],
    picked = Object.fromEntries(attributes.map(k => [k, obj[k]]));

console.log(picked);