0

I need to flatten an array where each item contains a nested object, as below:

[
  {
    a: "x",
    b: { b1: "x1", b2: "x2"}
  },
  {
    a: "y",
    b: { b1: "y1", b2: "y2"}
  }
]

to

[
  {
    a: "x",
    b1: "x1", 
    b2: "x2"
  },
  {
    a: "y",
    b1: "y1",
    b2: "y2"
  }
]

This here is the closest to what I'm looking for https://stackoverflow.com/a/33037683/4217097 However, I'm not sure how to use that solution for an array, as it only return the last item of the array when I tried applying it.

  • 1
    Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder May 29 '20 at 15:48
  • 1
    Create [this function](https://stackoverflow.com/a/55251598/3082296) and call `const newArray = yourArray.map(flattenObject)` – adiga May 29 '20 at 16:12

1 Answers1

2

You can do something like:

const source = [
  {
    a: "x",
    b: { b1: "x1", b2: "x2"}
  },
  {
    a: "y",
    b: { b1: "y1", b2: "y2"}
  }
]

const transformed = source.map(item => ({ ...item.b, a: item.a }));

console.log(transformed)

Map your source to a new object by grabbing a and spreading b into it.