【问题标题】:从对象数组中获取一维数组
【发布时间】:2022-01-23 16:31:00
【问题描述】:

我有以下对象数组:

const input = [
  { key1: 1, key2: 1, key3: 5 },
  { key1: 2, key2: 5, key3: 6 },
  { key1: 4, key2: 6, key3: 7 },
  { key1: 7, key2: 8, key3: 9 },
];

我只想遍历一个对象数组并将所有值收集到一个一维数组中,如下所示:

const output = [1, 1, 5, 2, 5, 6, 4, 6, 7, 7, 8, 9];

有人可以帮忙解决这个问题吗?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

如果键始终按该顺序排列,您可以使用 Object.values 作为对 flatMap 的回调

const output = input.flatMap(Object.values)

const input = [
  { key1: 1, key2: 1, key3: 5 },
  { key1: 2, key2: 5, key3: 6 },
  { key1: 4, key2: 6, key3: 7 },
  { key1: 7, key2: 8, key3: 9 },
];

const output = input.flatMap(Object.values)

console.log(output)

依赖对象中键的顺序通常不是一个好主意。您可以解构您需要的所有属性并按顺序展平它们:

input.flatMap(({ key1, key2,  key3 }) => [key1, key2, key3])

创建一个键数组,使其更具动态性:

const keys = ["key1", "key2", "key3"]
const output = input.flatMap(o => keys.map(k => o[k]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多