best way to convert object with arrays to array wi

2020-04-11 06:33发布

问题:

what is the best way to convert an object of arrays to an array of objects and vice-versa

{
  category : ['a','b','c'],
  title : ['e','f','g'],
  code : ['z','x','v']
}

To

[
  {
    category : 'a',
    title : 'e',
    code : 'z'
  },
  {
    category : 'b',
    title : 'f',
    code : 'x'
  },
  {
    category : 'c',
    title : 'g',
    code : 'v'
  },
]

回答1:

You could use two function for generating an array or an object. They works with

  • Object.keys for getting all own property names,

  • Array#reduce for iterating an array and collecting items for return,

  • Array#forEach just fo itarating an array.

function getArray(object) {
    return Object.keys(object).reduce(function (r, k) {
        object[k].forEach(function (a, i) {
            r[i] = r[i] || {};
            r[i][k] = a;
        });
        return r;
    }, []);
}

function getObject(array) {
    return array.reduce(function (r, o, i) {
        Object.keys(o).forEach(function (k) {
            r[k] = r[k] || [];
            r[k][i] = o[k];
        });
        return r;
    }, {});
}

var data = { category: ['a', 'b', 'c'], title: ['e', 'f', 'g'], code: ['z', 'x', 'v'] };

console.log(getArray(data));
console.log(getObject(getArray(data)));
.as-console-wrapper { max-height: 100% !important; top: 0; }



回答2:

You can use map() and forEach()

var obj = {
  category : ['a','b','c'],
  title : ['e','f','g'],
  code : ['z','x','v']
}

var result = Object.keys(obj).map(function(e, i) {
  var o = {}
  Object.keys(obj).forEach((a, j) => o[a] = obj[a][i])
  return o
})

console.log(result)



回答3:

Here is solution using reduce method and arrow function.

var obj={
  category : ['a','b','c'],
  title : ['e','f','g'],
  code : ['z','x','v']
}
var result=obj[Object.keys(obj)[0]].reduce((a,b,i)=>{
  var newObj={};
  Object.keys(obj).forEach(function(item){
     newObj[item]=obj[item][i];
  });
  return a.concat(newObj);
},[]);
console.log(result);