【问题标题】:Change objects in nested structure using map function使用 map 函数更改嵌套结构中的对象
【发布时间】:2022-01-17 05:56:29
【问题描述】:

我正在尝试更改嵌套地图函数中的对象。我有一组包含嵌套数据的对象。

如果我尝试这样做,数据结构正在发生变化。我得到数组数组。我在这里只需要为每个对象添加一个属性“级别”。是否可以使用嵌套的地图函数来做到这一点?

const res = data.map(itemA => ({ ...itemA,
    level: 'a'
  })
  .subA.map(itemB => ({ ...itemB,
    level: 'b'
  })))

console.log(res)
<script>
  let data = [{
      name: 'testA1',
      subA: [{
          name: 'testB1',
          subB: [{
            name: 'testC1',
            subC: []
          }]
        },
        {
          name: 'testB2',
          subB: [{
            name: 'testC1',
            subC: []
          }]
        }
      ]
    },
    {
      name: 'testA2',
      subA: [{
        name: 'testB1',
        subB: [{
          name: 'testC1',
          subC: [{
            name: 'testD1',
            subD: []
          }]
        }]
      }]
    }
  ]
</script>

【问题讨论】:

  • 遗漏了一个逗号。我给你做了一个sn-p
  • 您能否提供一个示例,说明您的示例的结果应该是什么样的?

标签: javascript nested javascript-objects


【解决方案1】:

其实我是这样弄的:

const res = data.map(itemA => (
  {...itemA, level: 'a', subA: itemA.subA.map(itemB => (
    {...itemB, level: 'b', subB: itemB.subB.map(itemC => (
      {...itemC, level: 'c'}
    ))}
  ))}
))
console.log(res)
<script>
  let data = [{
      name: 'testA1',
      subA: [{
          name: 'testB1',
          subB: [{
            name: 'testC1',
            subC: []
          }]
        },
        {
          name: 'testB2',
          subB: [{
            name: 'testC1',
            subC: []
          }]
        }
      ]
    },
    {
      name: 'testA2',
      subA: [{
        name: 'testB1',
        subB: [{
          name: 'testC1',
          subC: [{
            name: 'testD1',
            subD: []
          }]
        }]
      }]
    }
  ]
</script>

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • 你的答案只适用于c级
【解决方案2】:

你可以使用递归函数吗?

let data = [{ name: 'testA1', subA: [{ name: 'testB1', subB: [{ name: 'testC1', subC: [] }] }, { name: 'testB2', subB: [{ name: 'testC1', subC: [] }] } ] }, { name: 'testA2', subA: [{ name: 'testB1', subB: [{ name: 'testC1', subC: [{ name: 'testD1', subD: [] }] }] }] } ]

function addprop(arr, level){
    arr.map(x=>{
        const match = Object.keys(x).find(element => {
            if (element.includes('sub')) {
              return true;
            }
          });
          addprop(x[match], level+1)
    })
    return arr.map(x=>(x.level=level,x))
}

console.log(addprop(data, 1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 2018-09-13
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2021-11-28
    相关资源
    最近更新 更多