user3440030 user3440030 - 2 months ago 15
Javascript Question

How to converting format json in react JS?

I want to convert JSON format in JavaScript like this:

{
"a": [5,1,2],
"b": [4,0,3],
"c": [1,1,4]
}


to

[
{'a':5,'b':4,'c':1},
{'a':1,'b':0,'c':1},
{'a':2,'b':3,'c':4}
]


How to solve this?

Answer Source

Here you go:

const obj = {
  "a": [5,1,2],
  "b": [4,0,3],
  "c": [1,1,4] 
};

const convert = (obj) => {
  let res = [];
  const keys = Object.keys(obj);
  if (!keys.length) return [];
  for (let i = 0; i < obj[keys[0]].length; i++) {
    let nextObj = {};
    keys.forEach(key => {
      nextObj[key] = obj[key][i];
    });
    res.push(nextObj);
  }
  return res;
}

console.log(convert(obj))