1

If I have an array in the following format:

[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"

How could I map that into an array using the following format:

[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"

I've tried using flatten functions as described here: Merge/flatten an array of arrays in JavaScript? but i'm not sure how i'd set the key for each flattened child element.

2
  • For what you are doing, you are not really simply flattening an array, but creating a brand new array from a mixture of arrays and properties. Commented Sep 26, 2017 at 8:52
  • 1
    Please post valid sample data.
    – baao
    Commented Sep 26, 2017 at 8:53

1 Answer 1

1

I'm not sure if the data structure is correct as you refuse to post it, but if I'm guessing right you can get the desired result with a reduce, map combination

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));

Not the answer you're looking for? Browse other questions tagged or ask your own question.