如何在打字稿中展平2D数组?

时间:2017-09-26 08:47:50

标签: arrays typescript flatten

如果我有以下格式的数组:

[0]:
    ["id_1"]:
        prop1: "abc"
        prop2: "def" 
    ["id_2"]:
        prop1: "ghi"
        prop2: "jkl"
[1]:
    ["id_3"]:
        prop1: "mno"
        prop2: "pqr" 
    ["id_4"]:
        prop1: "stu"
        prop2: "vwx"

如何使用以下格式将其映射到数组中:

[0]:
    key: "id_1"
    prop1: "abc"
    prop2: "def" 
[1]:
    key: "id_2"
    prop1: "ghi"
    prop2: "jkl"
[2]:
    key: "id_3"
    prop1: "mno"
    prop2: "pqr" 
[4]:
    key: "id_4"
    prop1: "stu"
    prop2: "vwx"

我已尝试使用此处所述的展平功能:Merge/flatten an array of arrays in JavaScript? 但我不确定如何为每个扁平的子元素设置密钥。

1 个答案:

答案 0 :(得分:0)

我不确定数据结构是否正确,因为您拒绝发布,但如果我猜对了,您可以使用reduce,map组合获得所需的结果



let arr = [
    [{id_1: {prop1: 'abc', prop2: 'def'}}, {id_2: {prop1: 'ghi', prop2: 'jkl'}}],
    [{id_3: {prop1: 'abc', prop2: 'def'}}, {id_4: {prop1: 'ghi', prop2: 'jkl'}}]
];


function flatten(arr) {
  return arr.reduce((a, b) => {
    return a.concat(b.map(e => {
      let key = Object.keys(e)[0];
      return Object.assign({
        key
      }, e[key]);
    }))
  }, [])
}

console.log(flatten(arr));