循环内循环lodash

时间:2018-09-02 07:38:07

标签: javascript loops lodash

我有一个数组,其构建方式如下:

"list": [
    {
        "insideList": [{"code": "0", "image": "./images/1"},
                    {"code": "1", "image": "./images/2"},
                    {"code": "2", "image": "./images/3"}],
        "bucket": "info",
        "instructions": "first set".\n",
        "color": "rgb(242, 242, 140)",
        "id": "a",
        "text": "first quest"
    },
   ...

我正在尝试用lodash将此列表弄平,但是当第一张地图也可以执行操作时,我不知道如何在地图内部进行映射。 那是我为外循环所做的:

var withIndex = _.map(list,(item, i) => ({

      [`iv_${i}_text`]: item.text,
      [`iv_${i}_instructions`]: item.instructions,
      [`iv_${i}_color`]: item.color,
      [`iv_${i}_id`]: item.id,
      [`iv_${i}_bucket`]: item.bucket,
    }));

但是现在我想在“方面”列表上添加内部循环并构建如下所示的东西:

 var withIndex = _.map(list,(item, i) => ({
  [`iv_${i}_text`]: item.text,
  [`iv_${i}_instructions`]: item.instructions,
  [`iv_${i}_color`]: item.color,
  [`iv_${i}_id`]: item.id,
  [`iv_${i}_bucket`]: item.bucket,
  [`iv_${i}_a_0_code`]: item.insideList[0].code,       
  [`iv_${i}_a_0_image`]: item.insideList[0].image,  
  [`iv_${i}_a_1_code`]: item.insideList[1].code,       
  [`iv_${i}_a_1_image`]: item.insideList[1].image,
  [`iv_${i}_a_2_code`]: item.insideList[2].code,       
  [`iv_${i}_a_2_image`]: item.insideList[2].image
}));

可以使用lodash做这样的事情吗?

var withIndex = _.map(list,(item, i) => ({
      [`iv_${i}_text`]: item.text,
      [`iv_${i}_instructions`]: item.instructions,
      [`iv_${i}_color`]: item.color,
      [`iv_${i}_id`]: item.id,
      [`iv_${i}_bucket`]: item.bucket,

然后在这里绘制另一张地图:

 _map(insideLoop, (item, j)=> ({
      [`iv_${i}_a_{j}_code`]: item.insideList[0].code,       
      [`iv_${i}_a_{j}_image`]: item.insideList[0].image,  
      [`iv_${i}_a_{j}_code`]: item.insideList[1].code,       
      [`iv_${i}_a_{j}_image`]: item.insideList[1].image,
      [`iv_${i}_a_{j}_code`]: item.insideList[2].code,       
      [`iv_${i}_a_{j}_image`]: item.insideList[2].image
    }));

1 个答案:

答案 0 :(得分:2)

减少(累积)对象属性应该可以解决问题,然后只需合并两个对象即可:

var withIndex = _.map(list, (item, i) => _.assign(
  {
    [`iv_${i}_text`]: item.text,
    [`iv_${i}_instructions`]: item.instructions,
    [`iv_${i}_color`]: item.color,
    [`iv_${i}_id`]: item.id,
    [`iv_${i}_bucket`]: item.bucket,
  },
  _.reduce(item.insideList, (acc, x, j) => {
    acc[`iv_${i}_a_${j}_code`]: x.code
    acc[`iv_${i}_a_${j}_image`]: x.image
    return acc
  }, {})
));

而且您根本不需要 lodash (本机功能更快):

var withIndex = list.map((item, i) => Object.assign(
  {
    [`iv_${i}_text`]: item.text,
    [`iv_${i}_instructions`]: item.instructions,
    [`iv_${i}_color`]: item.color,
    [`iv_${i}_id`]: item.id,
    [`iv_${i}_bucket`]: item.bucket,
  },
  item.insideList.reduce((acc, x, j) => {
    acc[`iv_${i}_a_${j}_code`]: x.code
    acc[`iv_${i}_a_${j}_image`]: x.image
    return acc
  }, {})
));