2
pops = [
    [
      {
        key: 'test1',
        value: '0'
      }
    ],
    [
      {
        key: 'test2',
        value: '0'
      },
      {
        key: 'test3',
        value: '0'
      }
    ]
  ];

need to convert into this format

formated =
[{
 'test1':'0',
},
{
 'test2':'0',
 'test3':'0'
}]

I tried to solve the problem with this code but had no luck. can anyone help me to solve this problem? Thank you.

let formated = []
let count=0
for(let item of this.pops){
 
  for(let prop of item){
   formated[count].push(prop.key:prop.value)
  }
  count++;
}

1 Answer 1

3

This can be achieved with a combination of map and reduce:

const pops = [
    [
      {
        key: 'test1',
        value: '0'
      }
    ],
    [
      {
        key: 'test2',
        value: '0'
      },
      {
        key: 'test3',
        value: '0'
      }
    ]
  ];
  
const formatted = pops.map(i =>  i.reduce( (acc,x) => ({...acc,[x.key]:x.value}),{}));

console.log(formatted);

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.