使用Object.assign

时间:2016-11-25 09:34:21

标签: reactjs redux

我目前的状态是:

S1:

[
{primaryKey : 123,
 otherKeys: value
:
otherkeys... 
},
{
 primaryKey : 345,
 otherKeys: value
 :
 :otherKeys...
},
{
primarykey : 567,
otherKeys...
},
{
primaryKey : 789,
otherKeys...
}
]

我想用

更新索引0和索引1的元素

S2:

[
{primaryKey : 123,
 updatedKeys: value
:
otherkeys... 
},
{
 primaryKey : 345,
 updatesKeys: value
 :
 :otherKeys...
}
]

更新后,状态应如下所示:

[
{primaryKey : 123,
 updatedKeys: value
:
otherkeys... 
},
{
 primaryKey : 345,
 updatedKeys: value
 :
 :otherKeys...
},
{
primarykey : 567,
otherKeys...
},
{
primaryKey : 789,
otherKeys...
}
]

我尝试在他们的primaryKey匹配上迭代状态对象和Object.assign到新的对象。

state.map( (data1) =>{
    s2.map((data) => {
     if(data1.primaryKey === data.primaryKey){
       data1 = Object.assign({}, data);
     }
    })
})

我很困惑,除了两次使用地图之外,还有更好的方法吗?

3 个答案:

答案 0 :(得分:0)

对于修改数组元素和ES6语法, spread 运算符非常惯用:

var newArray = [
  ...list.slice(0, indexOfElement),
  amendedElement
  ...list.slice(indexOfElement+1)
];

所以,你必须找到元素的索引,创建一个克隆并修改它,然后返回一个如上构造的新数组。

fiddle

注意:

https://egghead.io/lessons/javascript-redux-avoiding-array-mutations-with-concat-slice-and-spread

它解释得非常出色。

答案 1 :(得分:0)

如果您愿意将数据结构从一个对象数组更改为一个由id键入的对象,那么您可以进一步简化更新。

简单地说:您使用主键作为元素wach的键控id。这与普通数组的索引很相似,但意味着您可以用任何有效的标识符替换该数字。

  

这样做可以让您使用以下方式更新您的州:

s1 = {
  ...s1,
  ...s2
}

您必须对州进行的更改:

将您当前的状态s1修改为:

// it is now an object whose keys are now the primary key
{
  [123]{
    otherKeys: value
    :
    otherkeys... 
    },
  [345]{
     otherKeys: value
     :
     :otherKeys...
    },
  [567]{
    otherKeys...
    },
  [789]{
    otherKeys...
  }
}

修改你的新s2如下:

// again, it is now an object whose keys are now the primary key
{
  [123]{
    updatedKeys: value
    :
    otherkeys... 
  },
  [345]{
    updatedKeys: value
    :
    :otherKeys...
  }
}

使用顶部建议的传播语法,您可以使用s2将s1更新为以下内容:

{
  [123]{
    updatedKeys: value
    :
    otherkeys... 
  },
  [345]{
    updatedKeys: value
    :
    :otherKeys...
  },
  [567]{
    otherKeys...
  },
  [789]{
    otherKeys...
  }
}

回应@ nitte93user3232918关于如何从s1对象数组转换为对象对象的评论中的额外问题

let newS1 = {};
s1.map((val,i) => {
  newS1 = {
    ..s1,
    [val.primarykey]:val
  }
});

答案 2 :(得分:0)

使用Object.assign应该是一种方便的方法。

如果您的状态是数组形式,那么这应该是最佳方式:

var newState = Object.assign([], s1, s2);

这将s2的更新状态值组合成s1。

请参阅此示例:http://www.es6fiddle.net/ivxsln91/