Artifex
Artifex

Reputation: 81

React reducer (add object key to object)

I have an object like this:

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

and I want to write reducer to get object like this:

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

My reducer:

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

Please help me out, I feel like I've tried everything.

Upvotes: 0

Views: 418

Answers (3)

Chtioui Malek
Chtioui Malek

Reputation: 11515

You should pass your fruits object in action.fruits, and in your reducer :

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

and your new state will contain the fruits object as you want it.

Upvotes: 0

felixmosh
felixmosh

Reputation: 35503

You can achieve that using Object.keys, it returns you an Array with all the 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);

Upvotes: 1

js_248
js_248

Reputation: 2112

You should also be having a Action file corresponding to this reducer. So in Action you will be getting this object

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

you can iterate through fruits and add new name to each object and reuturn this final object. All logic modifications should be done in Action file.

Upvotes: 0

Related Questions