如何通过修改返回所有值

时间:2017-09-04 15:20:43

标签: javascript ecmascript-6

这里我想通过修改列表中的一个对象来返回所有列表。 我尝试过以下代码。

state = state.filter(item => {
  if (item.name === action.value)
    item.completed = true;
}); //I want to return all the state as same by modifying item.completed.

4 个答案:

答案 0 :(得分:1)

可以使用对象分配:

state = state.map(
  obj => Object.assign({},obj, { completed: obj.completed ||  item.name === action.value})
);

答案 1 :(得分:1)

我认为你真正想要的是

// create new objects with their .completed property set to the condition
state = state.map(item => Object.assign({}, item, {completed: item.name === action.value}))
// or to keep previous true values (only "updating" those that match):
state = state.map(item => item.name === action.value
  ? Object.assign({}, item, {completed: true})
  : item)

或者如果你真的想修改对象,那么就简单

for (const item of state)
  if (item.name === action.value)
    item.completed = true;

会这样做。

答案 2 :(得分:0)

var action = {
  value: 'test'
}

var state = [
  {name: 'test'},
  {name: 'aaa'},
  {name: 'ccc', completed: true},
];

state = state.map(item => {
  if (item.completed || item.name === action.value) {
    item.completed = true;
  }
  return item;
});
console.log(state);

答案 3 :(得分:0)

您必须在return函数中使用callback语句。

state = state.filter(item => {
        if (item.name === action.value)
           item.completed = true;
         return item.completed;
});