嵌套对象,数组组合

时间:2020-04-16 12:15:37

标签: arrays object

所以我有一个难题。 我有下一个代码

  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可以更改,并且我需要创建与object_key存在次数一样多的对象。

我已经尝试了一些方法,但是我不知道什么时候涉及到这些东西....我只是做不到,那是当您以react而不是Java脚本开始时发生的事情:)

1 个答案:

答案 0 :(得分:0)

好吧,所以我设法用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);