Home > Net >  How to merge object with same key in react
How to merge object with same key in react

Time:12-17

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

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

Instead of using an array, use an object, it will overwrite the property.

const [data, setData] = useState({});

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

  • Related