Home > front end >  Pushing New value to Array of Objects while keeping old one intact React Js Next Js
Pushing New value to Array of Objects while keeping old one intact React Js Next Js

Time:05-22

I have a JSON file with image Names. I want to store data in a Key-Value Object. I'm creating the key using regex to remove -img[image No]. I'm unable to store all image Names in the array. When I add a new element it overwrites it to the previous value.

How can I push new data in an array without wiping off previously-stored data?

Data Document

[
    "apple-img1",
    "apple-img2",
    "apple-img3",
    "apple-img4",
    "apple-img5",
    "dell-img1",
    "dell-img2",
    "dell-img3",
    "hp-img1",
    "hp-img2"
]

My Code

content.map((contentInfo) => {
  let key = contentInfo.replace(/-img\d$/, "") //Return Company Name without -i{Digit} For Example apple-img1 whould be apple
  let imgName = contentInfo //Name of the Image
            
  data[key] = {
      Images: imgName //Append New Image 2 Array Instead of OverWriting Them
  }
  console.log(data);
})

Current Output

{
    "apple": {
        "Images": [
            "apple-img5"
        ]
    },
    "dell": {
        "Images": [
            "dell-img3"
        ]
    },
    "hp": {
        "Images": [ 
            "hp-img2"
        ]
    }
}

Expected Output

{
    "apple": {
        "Images": [
            "apple-img1",
            "apple-img2",
            "apple-img3",
            "apple-img4",
            "apple-img5"
        ]
    },
    "dell": {
        "Images": [
            "dell-img1",
            "dell-img2",
            "dell-img3"
        ]
    },
    "hp": {
        "Images": [ 
            "hp-img1",
            "hp-img2"
        ]
    }
}

CodePudding user response:

The spread operator can be used for adding values to an array.

content.map((contentInfo) => {
  let key = contentInfo.replace(/-img\d$/, ''); //Return Company Name without -i{Digit} For Example apple-img1 whould be apple
  let imgName = contentInfo; //Name of the Image

  data[key] = {
    Images: [...data[key].Images, imgName], //Append New Image 2 Array Instead of OverWriting Them
  };
  console.log(data);
});

CodePudding user response:

You can use the spread operator to accomplish this task

content.map((contentInfo) => {
            let key = contentInfo.replace(/-img\d$/, "") //Return Company Name without -i{Digit} For Example apple-img1 whould be apple
            let imgName = contentInfo //Name of the Image
            
            data = {
               Images: {...imgName, key} //Append New Image 2 Array Instead of OverWriting Them
            }
            console.log(data);
})

This should work.

  • Related