Kamalesh Maity
Kamalesh Maity

Reputation: 129

How to merge object with same key in react

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

Upvotes: 2

Views: 1738

Answers (2)

maxshuty
maxshuty

Reputation: 10662

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

Upvotes: 2

abhishek sahu
abhishek sahu

Reputation: 648

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)

Upvotes: 0

Related Questions