如何从对象数组中获取键和子键?

时间:2020-05-12 11:07:51

标签: javascript arrays dictionary object

我有下面的对象数组。

const array = [{
  field1: "val1",
  field2: "val2",
  field3: {
    field1: "val1",
    field2: "val2"
  }
},
{
  field1: "val1",
  field2: "val2",
  field3: {
    field1: "val1"
  }
}]

我需要得到低于输出的值

const output = [{
  key: "field1",
  subkeys: []
},
{
  key: "field2",
  subkeys: []
},
{
  key: "field3",
  subkeys: ["field1", "field2"]
}]

我可以使用它来获取顶级字段

const keys = array.map(x => Object.keys(x)[0]);

但是无法访问内部的。

请帮助...谢谢!!!

4 个答案:

答案 0 :(得分:2)

您可以在顶层减少Object键的数组,然后检查该键的值是否为object-检索其嵌套键,否则只需保留空的子键数组

const array = [{
  field1: "val1",
  field2: "val2",
  field3: {
    field1: "val1",
    field2: "val2"
  }
},
{
  field1: "val1",
  field2: "val2",
  field3: {
    field1: "val1"
  }
}]

const result = array.map(item => {
  return Object.keys(item).reduce((acc, rec) => {
    if(typeof item[rec] === 'object') {
      return [...acc, {key: rec, subkeys: Object.keys(item[rec])}] 
    }
    return [...acc, {key: rec, subkeys: []}]
  }, [])
})

console.log(result)

答案 1 :(得分:2)

您可以通过查找嵌套对象来映射任何深度。

const
    getKeys = object => Object.keys(object).map(key => ({ 
        key, 
        subkeys: object[key] && typeof object[key] === 'object'
            ? getKeys(object[key])
            : []
    })),
    array = [{ field1: "val1", field2: "val2", field3: { field1: "val1", field2: "val2" } }, { field1: "val1", field2: "val2", field3: { field1: "val1" } }];

console.log(array.map(getKeys));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:2)

此解决方案使用 lodash 库。我提取了变量以提高可读性。此解决方案将适用于2个级别

const array = [
    {"field1":"val1","field2":"val2","field3":{"field1":"val1","field2":"val2"}},
    {"field1":"val1","field2":"val2","field3":{"field1":"val1","field4":"val1"}}
];

intermediateOutput = array.reduce(
  (accumulator, entry) => _.merge(accumulator, entry),
{});
// intermediateOutput = {"field1":"val1","field2":"val2","field3":{"field1":"val1","field2":"val2","field4":"val1"}}

const finalOutput = _.map(_.keys(intermediateOutput), (key) => {
  const value = intermediateOutput[key];
  return {key, subkeys: _.isObject(value) ? _.keys(value): [] }
})

console.log(finalOutput);
// finalOutput = [{"key":"field1","subkeys":[]},{"key":"field2","subkeys":[]},{"key":"field3","subkeys":["field1","field2","field4"]}]

答案 3 :(得分:1)

const output = []
for (let [key, value] of Object.entries(array)) {
    const subkeys = Object.keys(value)
    output.push({key, subkeys})
}

类似的东西吗?