开发者问题收集

更新数组中对象的值

2020-02-25
48

我尝试根据数据数组中的 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 ,我如何将 stationID: 26checked:false 更改为 checked:true

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);
Taki
2020-02-25