1

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??

2 Answers 2

2

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

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

Comments

0

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

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.