为了账号安全,请及时绑定邮箱和手机立即绑定

更新对象的嵌套数组内的属性

更新对象的嵌套数组内的属性

天涯尽头无女友 2023-09-21 17:18:53
我有这个数组,我想使用我尝试过的 id 更新特定对象内选定的frameId模板,但是如果我选择frameId = 1,则所有frameId 1模板都会被编辑,我只想要选定的id 。 sizes.map(size => {      if(size.id === id){        size.frames.map(frame => {          if(frame.frameId === frameId){            frame.template = {test: '101'}          }          return frame        })      }      return size    })[    {      id: 1,      name: 'Mrec',      frames: [        {          frameId: 1,          template: {},          img: [],        },        {          frameId: 2,          template: {},          img: [],        },      ],      active: false    },    {      id: 2,      name: 'Leaderboard',      frames: [        {          frameId: 1,          template: {},          img: [],        },        {          frameId: 2,          template: {},          img: [],        },      ],      active: false    }]
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

我认为正确的方法是这样的。(#edit:它适用于片段)


var id = 1,

frameId=2;

var sizes = [

    {

      id: 1,

      name: 'Mrec',

      frames: [

        {

          frameId: 1,

          template: {},

          img: [],

        },

        {

          frameId: 2,

          template: {},

          img: [],

        },

      ],

      active: false

    },

    {

      id: 2,

      name: 'Leaderboard',

      frames: [

        {

          frameId: 1,

          template: {},

          img: [],

        },

        {

          frameId: 2,

          template: {},

          img: [],

        },

      ],

      active: false

    }

]


sizes.map(size => {

        let frames;

        if (size.id === id) {

            frames = size.frames.map(frame => {

                if (frame.frameId === frameId) {

                    frame.template = { test: '101' }

                }

                return frame;

            })

        } else {

            frames = size.frames;

        }

        return {...size,frames}

    })

document.write(JSON.stringify(sizes))


查看完整回答
反对 回复 2023-09-21
  • 1 回答
  • 0 关注
  • 50 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信