繁体   English   中英

在Javascript中将对象数组转换为嵌套对象

[英]Convert Array of Objects to Nested Object in Javascript

我想使用递归函数将对象数组转换为嵌套对象。

目的是创建一个可以在我的初始数组的深度范围内工作的函数。 您可以在下面看到具有期望结果和代码段的初始数据,以尝试解决此问题。

初始对象数组

configurator: [
  {
    key: '-LLnLuLt6cn-vBpMWv-u',
    name: 'CONFIGURATOR_1',
    collections: [
      {
        key: '-LLnMWy69vACjys0QIGH',
        name: 'COLLECTION_1',
        options: [
          {
            key: '-LLnOxg5hsDYR-PcfjBT',
            name: 'OPTION_1',
          },
          {
            key: '-LLnP-O6TyHxIpPk9bCU',
            name: 'OPTION_2',
          },
        ],
      },
      {
        key: '-LLnMYNyJmhSCPB-8lL1',
        name: 'COLLECTION_2',
      },
    ],
  },
  { key: '-LLnLtLs7PjXSAW0PWCQ',
    name: 'CONFIGURATOR_2',
  }]

所需结果:嵌套对象

configurator: {
  '-LLnLuLt6cn-vBpMWv-u': {
    name: 'CONFIGURATOR_1',
    index: 0,
    collections: {
      '-LLnMWy69vACjys0QIGH': {
        name: 'COLLECTION_1',
        index: 0,
        options: {
          '-LLnOxg5hsDYR-PcfjBT': {
            name: 'OPTION_1',
            index: 0,
          },
          '-LLnP-O6TyHxIpPk9bCU': {
            name: 'OPTION_2',
            index: 1,
          },
        },
      },
      '-LLnMYNyJmhSCPB-8lL1': {
        name: 'COLLECTION_2',
        index: 1,
      },
    },
  },
  '-LLnLtLs7PjXSAW0PWCQ': {
    name: 'CONFIGURATOR_2',
    index: 1,
  },
}

我的尝试

这是到目前为止我尝试过的代码片段。 它仅适用于数组的第一个深度。 我相信这是要解决的挑战:如何动态地将对象添加/“推”到嵌套对象?

希望有人能帮忙。 干杯,朱利安。

 const data = { configurator: [{ key: '-LLnLuLt6cn-vBpMWv-u', name: 'CONFIGURATOR_1', collections: [{ key: '-LLnMWy69vACjys0QIGH', name: 'COLLECTION_1', options: [{ key: '-LLnOxg5hsDYR-PcfjBT', name: 'OPTION_1', }, { key: '-LLnP-O6TyHxIpPk9bCU', name: 'OPTION_2', }, ], }, { key: '-LLnMYNyJmhSCPB-8lL1', name: 'COLLECTION_2', }, ], }, { key: '-LLnLtLs7PjXSAW0PWCQ', name: 'CONFIGURATOR_2', } ] }; const format = (object) => { const result = {}; Object.keys(object).forEach((property) => { if (Array.isArray(object[property])) { object[property].forEach((test, index) => { const { key, ...content } = test; result[key] = { index, ...content }; format(content); }); } }); return result; }; const formated = format(data); console.log('@FORMATED__', formated); 

确实,这必须递归完成。 只需将数组reduce为一个对象。 对于每个对象,找到将数组作为值的键,然后将其应用于它们:

const format = array => 
    array.reduce((acc, obj, index) => {
        const {key, ...rest} = obj;
        Object.keys(rest)                                            // get the keys of the rest of the object
              .filter(key => Array.isArray(rest[key]))               // filter those that have arrays as values
              .forEach(key => rest[key] = format(rest[key]));        // for each one of them, format their array and assign them back to the rest object
        acc[key] = { ...rest, index };                               // create the new object and assign it to the accumulator
        return acc;
    }, {});

例:

 const format = array => array.reduce((acc, obj, index) => { const {key, ...rest} = obj; Object.keys(rest) .filter(key => Array.isArray(rest[key])) .forEach(key => rest[key] = format(rest[key])); acc[key] = { ...rest, index }; return acc; }, {}); const arr = [{"key":"-LLnLuLt6cn-vBpMWv-u","name":"CONFIGURATOR_1","collections":[{"key":"-LLnMWy69vACjys0QIGH","name":"COLLECTION_1","options":[{"key":"-LLnOxg5hsDYR-PcfjBT","name":"OPTION_1"},{"key":"-LLnP-O6TyHxIpPk9bCU","name":"OPTION_2"}]},{"key":"-LLnMYNyJmhSCPB-8lL1","name":"COLLECTION_2"}]},{"key":"-LLnLtLs7PjXSAW0PWCQ","name":"CONFIGURATOR_2"}]; console.log(format(arr)); 

注意:例如,如果可能有一些数组不只包含您要跳过的对象,则只需将过滤条件更改为:

.filter(key => Array.isArray(rest[key]))

至:

.filter(key => Array.isArray(rest[key]) && rest[key].every(item => item && typeof item === "object"))

哪一个在应用format之前先检查数组是否仅包含对象。

已编辑

function format(data) {
  var result = {};

  data.forEach(function(config, i) {
    var obj = {
        index: i
    }

    Object.keys(config)
        .forEach(function(key) {
            if (!Array.isArray(config[key])) {
                if (key != "key") obj[key] = config[key];
            } else {
                obj[key] = format(config[key]);
            }
        });

    result[config.key] = obj;
  });

  return result;
}
console.log(format(data));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM