neverrmind
neverrmind

Reputation: 17

How to rebuild an array from an existing one in JavaScript?

I have array of objects.

let data = [
  {
    "categories" : [
      {
        "products" : [
          {
            "name" : "Product 1"
          }
        ],
        "id" : 1369
      }
    ]
  }
];

I'd like to rebuild it like this:

let data = [
  {
    "products" : [
      {
        "name" : "Product 1"
      }
    ],
    "id" : 1369
  }
];

If I use .map(), I get array in array with object:

let data = [
  [
    {
      "products" : [
        {
          "name" : "Product 1"
        }
      ],
      "id" : 1369
    }
  ]
];

What the solution I must apply in this case?

Upvotes: 1

Views: 316

Answers (1)

Ori Drori
Ori Drori

Reputation: 192317

After using Array.map() flatten by spreading into Array.concat():

const data = [{"categories":[{"products":[{"name":"Product 1"}],"id":1369}]}];

const result = [].concat(...data.map(o => o.categories));

console.log(result);

Or use Array.reduce() with Array.concat():

const data = [{"categories":[{"products":[{"name":"Product 1"}],"id":1369}]}];

const result = data.reduce((r, o) => r.concat(o.categories), []);

console.log(result);

Upvotes: 1

Related Questions