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

Extract keys and values from object via an array of strings in javascript

我有一些 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(
  attributes.map(att => [att, obj[att]])
)
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))

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

您可以将想要的键与其值一起映射,并使用 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);

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