首页 > 解决方案 > 在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 谢谢!

标签: javascriptreduce

解决方案


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)


推荐阅读