best way to convert object with arrays to array with objects and viceversa

前端 未结 3 930
我寻月下人不归
我寻月下人不归 2021-01-14 12:45

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\'],
         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 13:28

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

提交回复
热议问题