javascript - 在javascript中使用reduce更改对象值
问题描述
我想用 reduce 改变对象的值,但结果与我的预期不同。
const test = [
{id: 'start', value: false},
{id: 'reject', value: false},
];
let ress;
const showModal = (which) => {
const res = test.reduce((res, s) => {
ress = {id: s.id, value: s.id === which ? (s.value = true) : (s.value = false)};
return ress;
}, []);
}
showModal('start');
console.log(ress);
实际结果:
{
"id": "reject",
"value":false
}
预期的:
[
{id: 'start', value: true},
{id: 'reject', value: false},
]
我不明白,为什么{id:'start', value:true}
被删除并
key
更改为string
类型。
这是工作示例:
https
://codepen.io/seoulsaram/pen/RwpJRPv?editors=1010
谢谢!
解决方案
const res = test.reduce((res, s) => {
ress = {
id: s.id,
value: s.id === which ? (s.value = true) : (s.value = false)
};
return ress; // returning always last object as result.
}, []);
此代码不正确,您总是推送最新的对象。
这里应该是什么样子(这不是实现这一目标的最佳方法,我只是让您的代码按您的预期工作):
const res = test.reduce((res, s) => {
const ress = {
id: s.id,
value: s.id === which ? (s.value = true) : (s.value = false)
}
res.push(ress)
return res; // return accumulator instead of object
}, []);
根据您的问题,看起来您正在寻找查找而不是减少。
这是解决您的情况的更好方法(改变原始数组):
const test = [
{id: 'start', value: false},
{id: 'reject', value: false},
]
const showModal = (which) => {
const found = test.find(e => e.id === which)
found.value = true // it will mutate object in array
}
showModal('start')
console.log(test)
另一种解决方案(不改变原始数组):
const test = [
{id: 'start', value: false},
{id: 'reject', value: false},
]
const showModal = (which) => test.map(e => e.id === which ? ({...e, value: true}) : {...e})
const res = showModal('start')
console.log('res', res)
console.log('test', test)
推荐阅读
- sql - 有时缺少数据时的行到列
- docker - 为什么 Logstash 不使用 gelf 的日志?
- erlang - Erlang OTP 21 如何禁用记录器控制台输出
- vaadin - 在 Vaadin 13 中,如何让椭圆出现在网格单元的左侧而不是右侧?
- php - 使用数组使用 jQuery、PHP 和 MySQL 插入多行
- mfc - 如何检查文件是否在 MFC 中被锁定?
- amazon-web-services - Cognito 上的自定义域
- wordpress - 我的联系表格 7 中的动态文本现在不起作用
- java - Countdownlatch 无异常挂起或终止
- html - 当文本对齐时,某些单词之间的间距在移动视图中太大了