lodash将带有数组的对象转换为对象数组

时间:2016-08-19 08:09:27

标签: 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

        }

1 个答案:

答案 0 :(得分:0)

您可以将_.map()参数和每个对象的名称放入一个对象数组中,然后_.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>

这是使用Array.prototype.map(),箭头函数和解构的ES6版本:

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>