2

My data is shaped like: [{size: ["large", "medium"]}, {color: ["red", "green"]}]

Form Page:

const optionSubmit = (e) => {
    const name = e.target.name;

    const storeValue = { [name]: productValue };
    addData(storeValue);
};
 

formContext page:

const addData= (newData) => {
    setData(() => [...data, newData]);
}

The problem is when I change size object example its showing like: [ {size: ["large", "medium"]}, {color: ["red", "green"]}, {size: ["large", "medium", "small"]} ]

I want this array to become like this:

[{color: ["red", "green"]},{size: ["large", "medium", small]}]
maxshuty
  • 9,708
  • 13
  • 64
  • 77

2 Answers2

2

You are taking your existing object and spreading it into a new array, and then adding the newData into that new array too. That is why you see this behavior.

Instead you can do this a couple of ways but something like this using Object.assign:

const addData= (newData) => {
  setData(() => Object.assign({}, data, newData};
}

Or if your newData is an object only containing the {size: []} then you could just do this:

const addData= (newData) => {
  setData(() => {...data, ...newData};
}
maxshuty
  • 9,708
  • 13
  • 64
  • 77
0

const myArr = [
    {size: ["large", "medium"]}, 
    {color: ["red", "green"]}, 
    {size: ["large", "medium", "small"]}
   ];
const result = [];
  myArr.forEach(e=>{
    const key = Object.keys(e)[0];
    const i = result.findIndex(r=>Object.keys(r)[0]==key);
    if(i>=0){
    result[i]= {...result[i],...e};
    }else{
    result.push(e)
    }
}) 
console.log(result)
abhishek sahu
  • 648
  • 4
  • 8