循环遍历对象数组并更改 JavaScript 中键的值

我有以下 json 数组,它是我从角度应用程序中的服务响应中解构的。


this.selectedList = [

  [

    {

      "meterNumber": "Z00001410",

      "utilType": "elec",

      "mprnGprn": "3100000334",

      "isChecked": true

    },

    {

      "meterNumber": "Z00001410",

      "utilType": "gas",

      "mprnGprn": "1000003344",

      "isChecked": true

    }

  ],

  [

    {

      "meterNumber": "Z00001410",

      "utilType": "elec",

      "mprnGprn": "1000003344",

      "isChecked": true

    }

  ],

  [

    {

      "meterNumber": "Z00001410",

      "utilType": "elec",

      "mprnGprn": "1000003344",

      "isChecked": true

    }

  ]

]

我需要做的是迭代列表并在单击事件上将isChecked值更改为 false。我尝试过以下方法


  selectAll(){

    this.selectedList = this.data.reportList.map((meter) => meter.pm);

    this.newList = this.selectedList.map((data) => {

      data.forEach(item => item.isChecked = false);

  });

  console.log(this.newList);

  }

上面的代码将值更改为 false,但是当我尝试控制台 newList 时,它是一个未定义值的数组。这是执行此操作的最佳方法还是我在这里做错了什么。


RISEBY
浏览 182回答 2
2回答

暮色呼如

您只需要从return data地图的每次迭代中添加:this.selectedList = [  [{      "meterNumber": "Z00001410",      "utilType": "elec",      "mprnGprn": "3100000334",      "isChecked": true    },    {      "meterNumber": "Z00001410",      "utilType": "gas",      "mprnGprn": "1000003344",      "isChecked": true    }  ],  [{    "meterNumber": "Z00001410",    "utilType": "elec",    "mprnGprn": "1000003344",    "isChecked": true  }],  [{    "meterNumber": "Z00001410",    "utilType": "elec",    "mprnGprn": "1000003344",    "isChecked": true  }]]selectAll = () => {  this.newList = this.selectedList.map((data) => {    data.forEach(item => {item.isChecked = false});    return data;  });  console.log(this.newList);}selectAll()

ibeautiful

请记住,使用地图时需要返回一个值。这是一个可行的解决方案:this.selectedList = [  [    {      "meterNumber": "Z00001410",      "utilType": "elec",      "mprnGprn": "3100000334",      "isChecked": true    },    {      "meterNumber": "Z00001410",      "utilType": "gas",      "mprnGprn": "1000003344",      "isChecked": true    }  ],  [    {      "meterNumber": "Z00001410",      "utilType": "elec",      "mprnGprn": "1000003344",      "isChecked": true    }  ],  [    {      "meterNumber": "Z00001410",      "utilType": "elec",      "mprnGprn": "1000003344",      "isChecked": true    }  ]]selectAll = () => {    this.selectedList = this.selectedList.map(subArray => {        subArray.forEach(_ => _.isChecked = false);        return subArray;    });    console.log(this.selectedList)}selectAll();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript