从对象数组中获取键:Javascript

时间:2019-06-23 18:33:02

标签: javascript ecmascript-6

在这种情况下,我只需要获取对象数组中的键。对象结构如下所示。我也尝试了一种方法,但是它似乎不起作用。有人可以帮我这个忙吗?

var arr = [
        { firstName: "aaaaa", status: 0, visits: 155 },
        { firstName: "aabFaa", status: 0, visits: 155 },
        { firstName: "adaAAaaa", status: 10, visits: 1785 },
        { firstName: "aAaaaa", status: 50, visits: 175 },
        { firstName: "aaaaa", status: 670, visits: 155 },
      ]

console.log([...new Set(arr.map(item => Object.keys(item)))]); //  This does not work

我希望输出仅为['firstName','status','visits']

3 个答案:

答案 0 :(得分:5)

Object.keys本身会返回一个数组,因此您的map创建一个数组数组。请改用flatMap

console.log(Array.from(new Set(arr.flatMap(Object.keys))))

或者,由于数组中的所有对象都具有相同的键,因此您可以采用第一个对象的键:

console.log(Object.keys(arr[0]))

(这也很明显,该代码仅适用于非空数组)

答案 1 :(得分:1)

您正在尝试从二维键数组创建Set。使用flatMap来获取数组中所有对象的键的扁平数组

[...new Set(arr.flatMap(item => Object.keys(item)))]

这是一个片段:

const arr = [
      { firstName: "aaaaa", status: 0, visits: 155 },
      { firstName: "aabFaa", status: 0, visits: 155 },
      { firstName: "adaAAaaa", status: 10, visits: 1785 },
      { firstName: "aAaaaa", status: 50, visits: 175 },
      { firstName: "aaaaa", status: 670, visits: 155 },
    ];
    
const uniqueKeys = [...new Set(arr.flatMap(Object.keys))]

console.log(uniqueKeys)

答案 2 :(得分:0)

Object.keys(arr[0])可能是最短的解决方案,假设arr中的每个对象都具有相同的键:

var arr = [{
    firstName: "aaaaa",
    status: 0,
    visits: 155
  },
  {
    firstName: "aabFaa",
    status: 0,
    visits: 155
  },
  {
    firstName: "adaAAaaa",
    status: 10,
    visits: 1785
  },
  {
    firstName: "aAaaaa",
    status: 50,
    visits: 175
  },
  {
    firstName: "aaaaa",
    status: 670,
    visits: 155
  },
]

let keys = Object.keys(arr[0]);

console.log(keys);