React reducer(将对象键添加到对象)

时间:2017-09-23 10:22:52

标签: javascript reactjs

我有一个这样的对象:

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

我想写reducer来获取这样的对象:

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
      }
  }

请帮助我,我觉得我已经尝试了一切。

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

您还应该拥有与此reducer相对应的Action文件。 因此,在Action中,您将获得此对象

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

你可以遍历水果并为每个对象添加新名称并重新开始这个最终对象。 所有逻辑修改都应在Action文件中完成。

答案 2 :(得分:0)

你应该在action.fruits和你的reducer中传递你的fruit对象:

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

并且您的新状态将包含您想要的水果对象。