更新数组中对象的值

时间:2020-02-25 14:17:33

标签: javascript reactjs

我正在尝试根据数据数组中的ID更新特定值。我正在尝试在Redux的reducer内执行此操作。

例如,我需要的是这样的东西

            case STATION_SELECT:
            const checkedGroupData = (data,id) => {
                    console.log(data);
                    console.log(id);
            }

            return {
                ...state,
                chargingStationGroups: Object.values(checkedGroupData(state.chargingStationGroups,action.id)),
            }

因此,data的console.log值如下所示

[
  0: 
     groupId: "31"
     groupName: "Test"
     stations: [
       0: {stationID: "26",name: "TestName",checked:false}
       1: {stationID: "28",name: "TestName2",checked:false}
     ]
  1: 
     groupId: "32"
     groupName: "Test332"
     stations: [
       0: {stationID: "29",name: "TestName1212",checked:false}
       1: {stationID: "30",name: "TestName122",checked:false}
     ]

]

因此,如果我的id的console.log是26,如何将checked:false的{​​{1}}更改为checked:true

1 个答案:

答案 0 :(得分:1)

您可以使用嵌套的Array.map并检查stationID是否与id返回true相匹配,如果不匹配,则返回原始的:

const checkedGroupData = (data, id) => {
  return data.map(o => ({
    ...o,
    stations: o.stations.map(s => ({
      ...s,
      checked: s.stationID === id ? true : s.checked
    }))
  }));
};

const data = [
  {
    groupId: "31",
    groupName: "Test",
    stations: [
      { stationID: "26", name: "TestName", checked: false },
      { stationID: "28", name: "TestName2", checked: false }
    ]
  },
  {
    groupId: "32",
    groupName: "Test332",
    stations: [
      { stationID: "29", name: "TestName1212", checked: false },
      { stationID: "30", name: "TestName122", checked: false }
    ]
  }
];

const result = checkedGroupData(data, "26");

console.log(result);