获取嵌套对象的键

时间:2019-10-29 11:48:24

标签: javascript reactjs

我需要一个简单的方法来获取嵌套对象的键,例如description。这是我的结构:

let data = [
  {
    name: "Apple",
    id: 1,
    alt: [{ name: "fruit1", description: "tbd1" }]
  },
  {
    name: "Banana",
    id: 2,
    alt: [{ name: "fruit2", description: "tbd2" }]
  },
  {
    name: "Blueberry",
    id: 3,
    alt: [{ name: "fruit3", description: "tbd3" }]
  }
];

4 个答案:

答案 0 :(得分:1)

您可以使用Object.keys(x)列出任何任意对象的键。关于嵌套,这只是知道要列出哪些嵌套索引并为其提供字段的一种情况。

您可能要考虑类似this

答案 1 :(得分:0)

要获取嵌套对象的键:

Object.keys(data[0].alt[0]) =>生成字符串数组[“ name”,“ description”]-不必按此顺序。

要获取描述码的值:

data[0].alt[0].description =>产生tbd1字符串。

要获取所有描述的数组:

data.map(obj => obj.alt[0].description)

不知道您的意思,所以给了我所有我能想到的选择。

答案 2 :(得分:0)

如果要使用键(包括嵌套键),可以像这样递归遍历数组/对象。

有两个可选参数使您可以:

  • 忽略数组部分,即skipArrays
  • 是否保留父对象键,即keepObjKeys

const isObject = (obj) => obj != null && obj.constructor.name === "Object";

let data = [
  { name: "Apple",     id: 1, alt: [{ name: "fruit1", description: "tbd1" }] },
  { name: "Banana",    id: 2, alt: [{ name: "fruit2", description: "tbd2" }] },
  { name: "Blueberry", id: 3, alt: [{ name: "fruit3", description: "tbd3" }] }
];

console.log(getKeys(data, false, false));
console.log(getKeys(data, true, true));

function getKeys(obj, keepObjKeys, skipArrays, keys=[], scope=[]) {
  if (Array.isArray(obj)) {
    if (!skipArrays) scope.push('[' + obj.length + ']');
    obj.forEach((o) => getKeys(o, keepObjKeys, skipArrays, keys, scope), keys);
  } else if (isObject(obj)) {
    Object.keys(obj).forEach((k) => {
      if ((!Array.isArray(obj[k]) && !isObject(obj[k])) || keepObjKeys) {
        let path = scope.concat(k).join('.').replace(/\.\[/g, '[');
        if (!keys.includes(path)) keys.push(path);
      }
      getKeys(obj[k], keepObjKeys, skipArrays, keys, scope.concat(k));
    }, keys);
  }
  return keys;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

答案 3 :(得分:0)

可以帮助您

let keys = Object.keys(yourObject);

键数组包含名称,说明