首页 > 解决方案 > change selected object value in an array of object

问题描述

So I have 2 arrays of objects. The first one is the main data and the second one is the filtered data.

main = [
{id:1,type:normal,qty:10,number:111},
{id:2,type:special,qty:10,number:222},
{id:3,type:normal,qty:10,number:333},
{id:4,type:normal,qty:10,number:111},
]
dispatch({ type: "MAIN_DATA", payload: main});

filter = main.filter((data) => {
      return data.number === state.number;
    }); 
dispatch({ type: "SPECIAL_DATA", payload: filter });

I only want to take data that has the same number as the state.number and then assign it to a new array of state. In this case, it matched with number:111.

const initialState = {
    mainData: [],
    filterData: [],
    finalData:[],
    number: 111
  };
  const [state, dispatch] = useReducer(reducer, initialState);

So far there is no problem with the code. But when I reassigned a value from the filterData and concat both arrays, all of the values changed.


if (state.filterData) {
   const data = state.filterData.filter((data) => {
   return (data.type = "special");
   }); 
}
dispatch({type: "FINAL_DATA",
payload: state.mainData.concat(state.receiveData)});

At first, I thought it's because of the concat but it wasn't. The problem is, all of the values from type key got replaced by special.

[
{id:1,type:special,qty:10,number:111},
{id:2,type:special,qty:20,number:222},
{id:3,type:special,qty:30,number:333},
{id:4,type:special,qty:10,number:111},
]

What I want to achieve is this

[
{id:1,type:special,qty:10,number:111},
{id:2,type:special,qty:20,number:222},
{id:3,type:normal,qty:30,number:333},
{id:4,type:special,qty:10,number:111},
]

Could someone tell me what is the problem with my code? Because I think I didn't do any changes with the original data, but how come it turned out like this?

Appreciate any kinda helps. thanks before

标签: javascriptarraysreactjs

解决方案


if (state.filterData) {
  const data = state.filterData.filter((data) => {
   return (data.type = "special");
  }); 
}

在上面的代码中,您使用赋值运算符(=)在 data.type 中分配“特殊”。使用比较运算符(== / ===)而不是赋值(=)

解决方案 -

   data.type === "special"

推荐阅读