2016-08-19 232 views
0

使用lodash,我想將包含數組的對象轉換爲對象數組。這裏有一個例子:lodash將數組轉換爲對象數組的對象

原來的對象:

[ 
    { 
    name:"name1" 
    params: [{param: "value1"}, {param: "value2"}] 
    }, 
    { 
    name:"name2" 
    params: [{param: "value3"}, {param: "value4"}] 
    } 
] 

改造後:

[ 
    {name:"name1", param: "value1"}, 
    {name:"name1", param: "value2"}, 
    {name:"name2", param: "value3"}, 
    {name:"name2", param: "value4"} 
] 

請告訴我最簡單的方式來實現這一目標?由於

[編輯]

直到現在我實現下面的功能,但我幾乎可以肯定,必須有我的問題更好的解決方案。

transform (res) { 

      const data = []; 

      _.each(res, (obj) => { 
       const params = _.pick(obj, ['params']); 
       const withoutParams = _.omit(obj, 'params'); 
       _.each(params.params, (param) => { 
        data.push(_.assign(param, withoutParams)); 
       }); 
      }); 
      console.log('data', data); 

      return data 

     } 

回答

0

可以_.map()每個對象的PARAMS和名稱輸入到對象的數組,然後_.flatMap()所有對象陣列成一個陣列:

var arr = [ 
 
    { 
 
    name:"name1", 
 
    params: [{param: "value1"}, {param: "value2"}] 
 
    }, 
 
    { 
 
    name:"name2", 
 
    params: [{param: "value3"}, {param: "value4"}] 
 
    } 
 
]; 
 

 
var newArr = _.flatMap(arr, function(obj) { 
 
    return _.map(obj.params, function(param) { 
 
    return { 
 
     name: obj.name, 
 
     param: param.param 
 
    }; 
 
    }); 
 
}); 
 

 
console.log(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

這是ES6版本使用Array.prototype.map(),箭頭功能和解構:

const arr = [ 
 
    { 
 
    name:"name1", 
 
    params: [{param: "value1"}, {param: "value2"}] 
 
    }, 
 
    { 
 
    name:"name2", 
 
    params: [{param: "value3"}, {param: "value4"}] 
 
    } 
 
]; 
 

 
const newArr = _.flatMap(arr, ({ 
 
    name, params 
 
}) => params.map(({ 
 
    param 
 
}) => ({ 
 
    name, param 
 
}))); 
 

 
console.log(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>