首页 > 解决方案 > 使用 es6 map 更改数组中元素的特定属性

问题描述

我的数据中有数组,我需要遍历数组,对于 id 与我需要编辑的数组匹配的任何数组,我只需要更改属性标题,它是一个带有另一个名称的字符串,例如, JOhn' 我正在迭代的数组的格式为

[{trackStatus: "ic", dates: Array(0), _id: "5b8510d4458a656d3a6cbf14", title: "martin"} ,{trackStatus: "ic", dates: Array(0), _id: "5b8510d4458a656d3a6cbf16", title: "rama" }]

现在我遵循了这个策略

array1: array1.map((topic) => {
      if( topic._id === action.payload.data._id){
          console.log('here');
          return{
              ...topic,
              title:'yama'
          }
      }
      return topic;
});

上述策略是否正确,因为我需要了解我面临的问题或错误是因为这部分还是其他原因?

标签: javascriptreactjs

解决方案


如果匹配,您可以简单地更改title属性:id

let array1 = [{trackStatus: "ic", dates: Array(0), _id: "5b8510d4458a656d3a6cbf14", title: "martin"} ,{trackStatus: "ic", dates: Array(0), _id: "5b8510d4458a656d3a6cbf16", title: "rama" }];
let action = {};
action.payload = {};
action.payload.data={};
action.payload.data._id = '5b8510d4458a656d3a6cbf14';

array1 = array1.map((topic) => {
   if( topic._id === action.payload.data._id){
       topic.title = 'yama';
   }
   return topic;
});
console.log(array1);


推荐阅读