如何正确更新/合并React Redux中的数组值

时间:2018-01-11 13:52:32

标签: javascript arrays reactjs ecmascript-6 redux

我的初始状态如下所示,如果添加新书或价格更改,则新更新的数组将来自服务,其结果需要在初始状态下合并。

const initialState = {
  booksData: [
    {"Code":"BK01","price":"5"},
    {"code":"BK02","price":"30"},
    {"code":"BK03","price":"332"},
    {"code":"BK04","price":"123"}
  ] 
};

从服务器更新了数组,更新了少量记录/新

data: [
  {"Code":"BK01","price":"10"},
  {"code":"BK02","price":"25"},       
  {"code":"BK05","price":"100"}
] 

更新后的状态应该在将更新后的数组与旧数组合并之后。

booksData: [
  {"Code":"BK01","price":"10"},
  {"code":"BK02","price":"25"},
  {"code":"BK03","price":"332"},
  {"code":"BK04","price":"123"},
  {"code":"BK05","price":"100"}
] 

4 个答案:

答案 0 :(得分:6)

我会过滤掉新数据中的旧数据元素,然后连接。

const oldBooks = booksData.filter(book => !newData.some(newBook => newBook.code === book.code));
return oldBooks.concat(newData);

请记住,您不能将值推入旧数组。在你的reducer中,你必须创建新的实例,这里是一个新的数组。 'concat'做到了。

答案 1 :(得分:1)

您可以先将数组合并在一起,然后reduce将其删除重复项



var booksData = [
   {"code":"BK01","price":"5"},
   {"code":"BK02","price":"30"},
   {"code":"BK03","price":"332"},
   {"code":"BK04","price":"123"}
   ] 

var newData = [
   {"code":"BK01","price":"10"},
   {"code":"BK02","price":"25"},       
   {"code":"BK05","price":"100"}
   ] 

const result = [...newData, ...booksData].reduce((res, data, index, arr) => {
  if (res.findIndex(book => book.code === data.code ) < 0) { 
      res.push(data);

  }  
  return res;
}, [])

console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用'Code'属性

合并两个数组并过滤
const initialState = {
    booksData: [
        { "Code": "BK01", "price": "5" },
        { "code": "BK02", "price": "30" },
        { "code": "BK03", "price": "332" },
        { "code": "BK04", "price": "123" }
    ]
};

const data =
[
    { "Code": "BK01", "price": "10" },
    { "code": "BK02", "price": "25" },
    { "code": "BK05", "price": "100" }
]


let newState = [...initialState.booksData, ...data];
newState = newState.filter((obj, pos, arr) => {
    return arr.map(mapObj => mapObj['Code']).indexOf(obj['Code']) !== pos;
});
console.log(newState);

答案 3 :(得分:0)

对象集合

通过迭代合并数组中索引在“父” filter 迭代器的当前索引之前的每个项目,对合并数组进行过滤以仅选择不存在的项目

const mergedUnique = [
    ...[{id:1}, {id:2}, {id:3}], 
    ...[{id:1}, {id:4}, {id:2}]
  ]
  .filter((item, idx, arr) => 
    !arr.some(({id}, subIdx) => subIdx < idx && id == item.id) 
  )

console.log( mergedUnique )

“简单”数组的基本技术

合并一些数组,并通过检查合并数组中当前项目的索引之前处是否存在相同项目,对它们进行过滤以仅选择不存在的项目。

lastIndexOf用于检查向后,如果当前值已经存在已经,这有助于以某种方式保持合并数组的顺序,从而可能是理想的,这只能通过检查向后而不是向前来实现。

跳过检查第一个项目-显然不是重复的。

const mergedUniqe = [...[1,2,3], ...[1,3,4,5,2]] // [1, 2, 3, 1, 3, 4, 5, 2]
  .filter((item, idx, arr) => 
    !~arr.lastIndexOf(item, idx-1) || !idx
  )
    
console.log( mergedUniqe )