1

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?

2
  • Try this data = data[0].categories Commented Apr 14, 2018 at 9:24
  • what if data or data[n].categories has two or more elements? What do you want then Commented Apr 14, 2018 at 9:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.