user3599302
user3599302

Reputation: 108

Merger chunks of array objects to single array

I have to merge chunk of arrays into single array with array of objects in Angularjs.

my input array will be like:

[
  [
    {
      "title": "asd",
      "description": "asd"
    },
    {
      "title": "asz",
      "description": "sd"
    }
  ],
  [
    {
      "title": "ws",
      "description": "sd"
    },
    {
      "title": "re",
      "description": "sd"
    }
  ],
  [
    {
      "title": "32",
      "description": "xxs"
    },
    {
      "title": "xxc",
      "description": "11"
    }
  ]
]

The above input array should be save like array of objects like below

[
  {
    "title": "asd",
    "description": "asd"
  },
  {
    "title": "asz",
    "description": "sd"
  },
  {
    "title": "ws",
    "description": "sd"
  },
  {
    "title": "re",
    "description": "sd"
  },
  {
    "title": "32",
    "description": "xxs"
  },
  {
    "title": "xxc",
    "description": "11"
  }
]

Please suggest me how can i achieve this.

Thanks a lot in advance

Upvotes: 2

Views: 64

Answers (3)

CertainPerformance
CertainPerformance

Reputation: 370889

You're just looking for a way to flatmap, which is easy with concat and spread:

const input=[[{"title":"asd","description":"asd"},{"title":"asz","description":"sd"}],[{"title":"ws","description":"sd"},{"title":"re","description":"sd"}],[{"title":"32","description":"xxs"},{"title":"xxc","description":"11"}]]
const output = [].concat(...input);
console.log(output);

Upvotes: 2

Mamun
Mamun

Reputation: 68943

You can use concat() and spread operator (...):

var arr = [
  [
    {
      "title": "asd",
      "description": "asd"
    },
    {
      "title": "asz",
      "description": "sd"
    }
  ],
  [
    {
      "title": "ws",
      "description": "sd"
    },
    {
      "title": "re",
      "description": "sd"
    }
  ],
  [
    {
      "title": "32",
      "description": "xxs"
    },
    {
      "title": "xxc",
      "description": "11"
    }
  ]
]

var res = [].concat(...arr);
console.log(res);

Upvotes: 2

Mohammad Usman
Mohammad Usman

Reputation: 39332

You can use .reduce() and .concat().

let data = [[{"title": "asd","description": "asd"},{"title": "asz","description": "sd"}],[{"title": "ws","description": "sd"},{"title": "re","description": "sd"}],[{"title": "32","description": "xxs"},{"title": "xxc","description": "11"}]];

let result = data.reduce((a, c) => a.concat(c), []);

console.log(result);

Upvotes: 5

Related Questions