Mansoor Ahmed
Mansoor Ahmed

Reputation: 77

Combine object with array as list of arrays

I have an Object as

var a ={
demo:[1,2,3],
demo1:[test1,test2,test3]
}`

I want to convert the above object into array of objects

var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}];`

can anyone help on this??

Upvotes: 1

Views: 51

Answers (2)

Hassan Imam
Hassan Imam

Reputation: 22524

You can use array#reduce to iterate through your array and using Object#keys() you can get the key of each object then iterate through each key and add to an accumulator object.

var a = [{"demo":"1", "demo1":"test1"},{"demo":"2", "demo1":"test2"},{"demo":"3", "demo1":"test3"}],
  result = a.reduce((r,o) => {
    Object.keys(o).forEach(k => {
      r[k] = r[k] || [];
      r[k].push(o[k]);
    });
    return r;
  },{});
console.log(result);

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68635

Iterate on the first array - demo, using Array#map function and then using the index of the first item access the demo1 appropriate item.

const a = {
   demo: [1, 2, 3],
   demo1: ['test1', 'test2', 'test3']
};

const mapped = a.demo.map((item, index) => ({ demo: item, demo1: a.demo1[index] }));

console.log(mapped);

Upvotes: 2

Related Questions