首页 > 解决方案 > 嵌套对象,数组组合

问题描述

所以我进退两难。我有下一个代码

  const loc = [
    { location_key: [32, 22, 11], autoassign: 1 },
    { location_key: [41, 42], autoassign: 1 }
  ];
  const bulkConfigs = [
    {
      dataValues: {
        config_key: 100,
      }
    },
    {
      dataValues: {
        config_key: 200,
      }
    }
  ];

我需要创建一个如下所示的对象:

  config_key: here get the config key from from bulkConfigs,
  location_key: here get the location_key,
  autoassign: 1

我也需要创建这个对象

                config_key: config_key,
                location_key: '',
                autoassign: 1,

与每个 config_key 的位置一样多,我的意思是在此示例中,来自 config_key: 200 我们将有 2 个这样的对象,而对于 config_key: 100 我们将有 3 个这样的对象。我想这可以通过 reduce 来完成……bulkConfigs 和 loc 可以有更多的对象,而不仅仅是 2 个对象,但是数量总是相同的,就像它们是 3 个 bulkConfigs 一样,也会有 3 个 loc,但 location_key 可能不同,一个可以有 7 个 location_key,其他 4 个,最后一个只有 1 个。

所以换句话说,数组的长度总是相同的,它们的顺序总是相同的,所以它们具有相同的索引。只有 location_key 可以更改,我需要创建与 location_key 一样多次的对象。

我已经尝试了一些东西,但我不知道什么时候涉及到这些东西......我就是做不到,当你从 react 而不是 java script 开始时会发生这种情况:)

标签: arraysobject

解决方案


好的,所以我设法使用 lodash 做到了这一点,这是我的解决方案,我知道它像地狱一样嵌套,可能这可以更容易地完成,但对于新手来说已经足够了。随意提供更优雅的解决方案。

如果您有类似的问题,这里是解决方案。一个代码沙箱,您可以使用: https ://codesandbox.io/s/epic-field-bdwyi?file=/src/index.js

import _ from "lodash";

const locs = [{ location_key: [32, 22, 11] }, { location_key: [41, 42] }];
const bulkConfigs = [
  {
    dataValues: {
      config_key: 100
    }
  },
  {
    dataValues: {
      config_key: 200
    }
  }
];

// map over the array of bulckConfigs and get indexes
const mergedArrays = _.map(bulkConfigs, (bulkConfig, i) => {
  // create the object that we need
  const objectNeed = {
    // flatMap over the locs array to get flat values from objects in it
    location_key: _.flatMap(locs, ({ location_key }, index) => {
      // match the indexs of both arrays
      if (index === i) {
        // return the location_key values for each config
        return location_key;
      } else {
        // compact to remove the undefinded values returned
        return _.compact();
      }
    }),
    config_key: bulkConfig.dataValues.config_key,
    autoassign: 1
  };

  return objectNeed;
});

// now we just need to crate the same object as many locations and use flatMap to flatten the objects
const allObjects = _.flatMap(mergedArrays, mergedArray => {
  const yy = _.map(mergedArray.location_key, location => {
    const zz = {
      location_key: location,
      config_key: mergedArray.config_key,
      autoassign: 1
    };
    return zz;
  });
  return yy;
});

console.log(allObjects);

还有更优雅的版本:)

const getConfigs = (locEl, index) => {
  return _.map(locEl.location_key, (locationKey) => {
    return {
      location_key: locationKey,
      config_key: bulkConfigs[index].dataValues.config_key,
      autoassign: 1,
    };
  });
};

const configLocations = _.chain(locs)
  .map(getConfigs)
  .flatten()
  .value();

console.log(configLocations);

推荐阅读