javascript - 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
解决方案
if (state.filterData) {
const data = state.filterData.filter((data) => {
return (data.type = "special");
});
}
在上面的代码中,您使用赋值运算符(=)在 data.type 中分配“特殊”。使用比较运算符(== / ===)而不是赋值(=)
解决方案 -
data.type === "special"
推荐阅读
- android-studio - Dart 的 SDK 在 /flutter 文件夹中的什么位置?
- android - 将多个传感器数据保存到 sqlite 数据库
- swift - 使用数组和 Firebase
- javascript - 如何获取 JavaScript 全局变量并将其发送到 php 文件中?
- groovy - Azure 架构扩展 - 错误消息:对象引用未设置为对象的实例
- python - 代码实现在不需要时自动变量
- php - 如何轻松注释 PHP+HTML 代码
- xml - 如何在 ImportXML 的 URL 中包含 Google 表格单元格引用
- php - 存储第一页的数据并在第二页使用它而不使用 PHP GET
- python - 从网上下载 ZIP 文件 (Python)