2017-09-23 34 views
0

我有一個這樣的對象:陣營減速(添加對象鍵對象)

const fruits = { 
    "Orange": { "price": 0.25, "inventory": 10}, 
    "Banana": { "price": 0.30, "inventory": 10}, 
    "Apple": { "price": 0.95, "inventory": 10}, 
} 

,我想寫減速讓對象是這樣的:

const fruits = { 
    "Orange": { name: "Orange", "price": 0.25, "inventory": 10}, 
    "Banana": { name: "Banana", "price": 0.30, "inventory": 10}, 
    "Apple": { name: "Apple", "price": 0.95, "inventory": 10}, 
} 

我減速機:

const fruitsByName = (state = {}, action) => { 
     switch (action.type) { 
     case "RECEIVE_FRUITS": 
     return action.products 
     default: 
     return state 
     } 
    } 

請幫助我,我覺得我已經嘗試了一切。

回答

0

您還應該有一個Action文件對應於這個reducer。 所以在Action你會得到這個對象

const fruits = { 
    "Orange": { "price": 0.25, "inventory": 10}, 
    "Banana": { "price": 0.30, "inventory": 10}, 
    "Apple": { "price": 0.95, "inventory": 10}, 
} 

您可以通過水果迭代,並添加新的名稱,每個對象和reuturn這個最終目標。 所有的邏輯修改應該在Action文件中完成。

1

您可以使用Object.keys來實現該功能,它會返回一個包含所有keys的數組。

const fruits = { 
 
    "Orange": { 
 
    "price": 0.25, 
 
    "inventory": 10 
 
    }, 
 
    "Banana": { 
 
    "price": 0.30, 
 
    "inventory": 10 
 
    }, 
 
    "Apple": { 
 
    "price": 0.95, 
 
    "inventory": 10 
 
    }, 
 
}; 
 

 
const result = Object.keys(fruits).reduce((res, currentKey) => { 
 
    res[currentKey] = { ...fruits[currentKey], 
 
    name: currentKey 
 
    }; 
 
    return res; 
 
}, {}); 
 

 
console.log(result);

0

你應該通過你的水果action.fruits對象,並在你的減速機:

case "RECEIVE_FRUITS": 
    let newFruits = {}; 
    for (const [key, value] of Object.entries(action.fruits)) { 
     newFruits[key] = {...value, name : key} 
    } 
    return {...state, fruits: newFruits}; 

和新的狀態將包含水果對象作爲你想要它。