0

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.

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.