首页 > 解决方案 > 遍历对象并插入元素

问题描述

假设我有这个:

const data = [
  {
    table: [
      [{
        textValue: 'One'
      },
      {
        textValue: 'Two',
        rows: 3
      },
      {
        textValue: 'Three',
        rows: 3
      },
      {
        textValue: 'Four'
      }],
      [{
        textValue: 'RED',
        rows: 2
      },
      {
        textValue: 'GREEN'
      },
      {
        textValue: 'BLUE',
        rows: 1
      }]
    ]
  }
];

我要追求的是它遍历对象的位置(Object.entries()会工作吗?)并看到它rows存在并插入X许多空''字符串,所以你会有类似的东西:

const data = [
  {
    table: [
      [{
        textValue: 'One'
      },
      {
        textValue: 'Two',
        rows: 3
      },
        '',
        '',
        '',
      {
        textValue: 'Three',
        rows: 3
      },
        '',
        '',
        '',
      {
        textValue: 'Four'
      }],
      [{
        textValue: 'RED',
        rows: 2
      },
        '',
        '',
      {
        textValue: 'GREEN'
      },
      {
        textValue: 'BLUE',
        rows: 1
      },
      ''
      ]
    ]
  }
];

我考虑过使用 afor in但是当需要推送元素时我不知道要编辑它的父对象。

标签: javascriptarraysobject

解决方案


您可以使用.map()and which 将根据给定对象.flatMap()的数量返回插入的字符串字符数组,该数组将被展平为结果数组:rows

const data = [{ table: [ [{ textValue: 'One' }, { textValue: 'Two', rows: 3 }, { textValue: 'Three', rows: 3 }, { textValue: 'Four' } ], [{ textValue: 'RED', rows: 2 }, { textValue: 'GREEN' }, { textValue: 'BLUE', rows: 1 } ] ] }];

const result = data.map(obj => ({
  ...obj,
  table: obj.table.map(arr =>
    arr.flatMap((iobj) => [iobj, ...Array(iobj.rows || 0).fill('')])
  )
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important;} /* ignore */


推荐阅读