用lodash展平嵌套的对象

用lodash展平嵌套的对象

本文介绍了用lodash展平嵌套的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用lodash进行以下操作时,我的头撞得井井有条.我有一个带有更多嵌套对象的对象数组,看起来像这样:

I'm banging my head against a well trying to do the following with lodash. I have an array of objects with more nested objects, which looks like this:

[{
    id: 123,
    name: 'John',
    summary1: {
        count: 3,
        sum: 10,
    },
    summary2: {
        count: 10,
        sum: 20
    },
},
...
]

我想将此数组的每个元素转换为如下形式:

I want to convert each element of this array into something like this:

[{
    id: 123,
    name: 'John',
    summary1_count: 3,
    summary1_sum: 10
    summary2_count: 10,
    summary2_sum: 20,
},
...
]

所以基本上,我想以某种方式扁平化"数组的每个元素,以便根据主键和子键确定对象键.如何使用lodash或纯JS完成此操作?

SO basically I want to "flatten" each element of the array, in a way such that object keys are determined based on the main and subkeys. How can I accomplish this using lodash or plain JS?

您可以假设示例中只有1个嵌套层.

You can assume there's just 1 level of nesting like in the example.

推荐答案

您可以通过遍历原始数组中每个项目的键,检查其类型,然后对其进行进一步迭代而无需lodash(或另一个库)来完成此操作内部键,建立新的键来保存正确的值.

You can do this without lodash (or another library) by iterating over the keys of each item in the original array, checking their type, and further iterating over their internal keys, building new keys to hold the right values.

const array = [{
  id: 123,
  name: 'John',
  summary1: {
    count: 3,
    sum: 10
  },
  summary2: {
    count: 10,
    sum: 20
  }
}];


let newArray = array.map(item => {
  let newObj = {};

  Object.keys(item).forEach(key => {
    if (typeof item[key] === 'object') {
      Object.keys(item[key]).forEach(innerKey => {
        newObj[`${key}_${innerKey}`] = item[key][innerKey];
      });
    } else {
      newObj[key] = item[key];
    }
  });

  return newObj;
});

console.log(newArray);

当然,这不一定很漂亮或灵活(遵循您对单个级别的假设).

Granted, this isn't necessarily very pretty or flexible (following your assumption of a single level deep).

这篇关于用lodash展平嵌套的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 00:36