1

I have a list of array of Objects. I need to concat the all the options items into one array. Here is the sample array of objects.

let data = [
  {
    name: "group1",
    options: [
      {
        item: "item1",
        price: 100
      },
      {
        item: "item2",
        price: 200
      },
      {
        item: "item3",
        price: 300
      }
    ]
  },
  {
    name: "group2",
    options: [
      {
        item: "item4",
        price: 101
      },
      {
        item: "item5",
        price: 201
      }
    ]
  },
  {
    name: "group3",
    options: [
      {
        item: "item6",
        price: 254
      },
      {
        item: "item7",
        price: 358
      }
    ]
  }
]

output like:


let options = [
  {
    item: "item1",
    price: 100
  },
  {
    item: "item2",
    price: 200
  },
  {
    item: "item3",
    price: 300
  },
  {
    item: "item4",
    price: 101
  },
  {
    item: "item5",
    price: 201
  },
  {
    item: "item6",
    price: 254
  },
  {
    item: "item7",
    price: 358
  }
]

2 Answers 2

5

You can do it with reduce:

const options = data.reduce((acc, item) => acc.concat(item.options), [])
Sign up to request clarification or add additional context in comments.

Comments

3

You can try with Array.prototype.flatMap()

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

let options = data.flatMap(d => d.options);

let data = [
  {
    name: "group1",
    options: [
      {
        item: "item1",
        price: 100
      },
      {
        item: "item2",
        price: 200
      },
      {
        item: "item3",
        price: 300
      }
    ]
  },
  {
    name: "group2",
    options: [
      {
        item: "item4",
        price: 101
      },
      {
        item: "item5",
        price: 201
      }
    ]
  },
  {
    name: "group3",
    options: [
      {
        item: "item6",
        price: 254
      },
      {
        item: "item7",
        price: 358
      }
    ]
  }
];


let options = data.flatMap(d => d.options);
console.log(options);

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.