簡體   English   中英

在Redux Reducer中更新和重新定位數組中的對象

[英]Update and reposition object in array in Redux reducer

const state = [
  {10: {a: 22, b: 33}},
  {12: {a: 20, b: 33}},
  {15: {a: 22, b: 34}},
  {5: {a: 21, b: 30}},
  {9: {a: 29, b: 33}},
]

狀態是上述對象的數組。 當應用更新對象時,該對象應流動到第一個位置。

例如,假設我們將上面的第二個對象(主鍵為12 ),然后復制並更新它,如下所示:

{12: {a: 45, b: 33}}

現在,我們要將其插入到數組中,結果如下:

const state = [
  {12: {a: 45, b: 33}},
  {10: {a: 22, b: 33}},
  {15: {a: 22, b: 34}},
  {5: {a: 21, b: 30}},
  {9: {a: 29, b: 33}},
]

我了解如何以一成不變的方式更新對象,但是我無法理解如何完成上述任務。

像這樣的東西?

 const state = [ {10: {a: 22, b: 33}}, {12: {a: 20, b: 33}}, {15: {a: 22, b: 34}}, {5: {a: 21, b: 30}}, {9: {a: 29, b: 33}}, ] // find the numerical index of the object with the specified "key" function findIndexOfKey(array, key){ return array.findIndex(function(el){return key in el}); } // modify object and move to front function editObjectAndMoveToFront(array, key, updatedValues){ // find index of object with key, for use in splicing var index = findIndexOfKey(array, key); // create the updated version of the specified object var originalObject = array[index]; var originalObjectValue = originalObject[key]; var editedObject = {}; editedObject[key] = Object.assign({}, originalObjectValue, updatedValues) // here is the new state, with the updated object at the front var newArray = [ editedObject, ...array.slice(0, index), ...array.slice(index + 1) ] return newArray } const newState = editObjectAndMoveToFront(state, 12, {a: 45, b: 33}) console.log(newState); 

您可以使用類似

// an update function, here it just adds a new key
// to the object
const update = (x) => ({
  ...x,
  hello: "world"
});

// a filter factory
const withId = (id) => (item) => Boolean(item[id]); // item with specific ids
const withoutId = (id) => (item) => !Boolean(item[id]); // others

const state = [
  {10: {a: 22, b: 33}},
  {12: {a: 20, b: 33}},
  {15: {a: 22, b: 34}},
  {5: {a: 21, b: 30}},
  {9: {a: 29, b: 33}},
];

const id = 5;
const newState = state
  .filter(withId(id))
  .map(update)
  .concat(state.filter(withoutId(id)));


console.log(JSON.stringify(newState, null, 4));

這是在要更新的項目和其余項目之間的狀態之間進行過濾,將更新應用於所選內容,並將未觸及的項目連接到它們。

在另一個具有相同想法的示例下,該示例說明您可以對多個項目執行更新:

const markAsDone = (todo) => ({
  ...todo,
  done: true
});
const isInGroup = (group) => (todo) => todo.group === group;
const not = (predicate) => (x) => !predicate(x);

const isWork = isInGroup("work");
const notWork = not(isWork);

const state = [
  {
    todo: "go shopping",
    group: "life"
  },
  {
    todo: "go work",
    group: "work",
  },
  {
    todo: "go sleep",
    group: "life"
  }
];

// get work related todos, mark as done and 
// append to todo list
const newState = state
  .filter(notWork)
  .concat(state
    .filter(isWork)
    .map(markAsDone));


console.log(JSON.stringify(newState, null, 4));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM