使用es6 map更改数组中元素的特定属性

时间:2018-08-28 10:41:10

标签: javascript reactjs

我的数据中有数组,我需要遍历该数组,对于ID与我需要编辑的数组匹配的任何数组,我只需要更改属性标题(该字符串是具有另一个名称的字符串)说,“乔恩” 我要迭代的数组的格式为

[{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;
});

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

2 个答案:

答案 0 :(得分:1)

如果与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);

答案 1 :(得分:0)

我假设5b8510d4458a656d3a6cbf14需要更新。

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

    array1.map((i) =>{
      if(i._id == '5b8510d4458a656d3a6cbf14') i.title = 'JOhn' 
    })
    console.log(array1)