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

前端 未结 3 928
我寻月下人不归
我寻月下人不归 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:25

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

提交回复
热议问题