score:1

Accepted answer

the map function is intended to be used when you want to apply some function over every element of the calling array. i think here it's better to use a foreach:

useeffect(() => {
    let initialprices = {};

    data.foreach(({ category, options }) => {
      initialprices = {
        ...initialprices,
        [category]: options[0].price,
      };
    });

    setselectedprice(initialprices);
}, []);

score:0

from what i can see in your case, is that you want to populate initialprices, and after that to pass it setselectedprice. the map method is not a solution, for you in this case, because this method returns an array. a safe bet in your case would a for in loop, a foreach, or a reduce function.

const data = [
  {

    category: "ball",
    options: [
      {
        price: "120.45"
      }
    ]
  },
  {

    category: "t-shirt",
    options: [
      {
        price: "12.45"
      }
    ]
  }
];

the foreach example:


let initialprices = {};

// category and options are destructured from the first parameter of the method
data.foreach(({ category, options}) => {
  initialprices[category] = options[0].price;
});

// in this process i'm using the clojure concept to add dynamically the properties

setselectedprice(initialprices);

the reduce example:

const initialprices = object.values(data).reduce((accumulatorobj, { category, options}) => {
        accumulatorobj[category] = options[0].price
  return accumulatorobj;
}, {});
setselectedprice(initialprices);

score:1

your map function should return something. here it's not the case so the error happens. maybe a reduce function will be more appropriate than map?

score:2

the map function must return a value. if you want to create a new object based on an array you should use the reduce function instead.

const reducer = (accumulator, { category, options }) => (
{...accumulator, [category]:options[0].price}
)
const modifieddata = data.reduce(reducer)

more information https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/reduce


Related Query

More Query from same tag