2

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

4 Answers 4

2

Output of Array.prototype.map() will again be an array. In your case, Array.prototype.reduce() is the ideal function to achive it:

const data = [
  "apple-img1",
  "apple-img2",
  "apple-img3",
  "apple-img4",
  "apple-img5",
  "dell-img1",
  "dell-img2",
  "dell-img3",
  "hp-img1",
  "hp-img2",
];

const output = data.reduce((prev, curr) => {
  // get the keyname
  const [keyName] = curr.split("-");
  if (prev[keyName]) {
    // If the property exists then push to Images array
    prev[keyName].Images.push(curr);
  } else {
    // If the property name does not exist,
    // create it and add the initial value in the format you want
    prev[keyName] = { Images: [curr] };
  }
  return prev;
}, {});

console.log(output);

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Images: {...imgName, key} spreads the characters
0

Best solution provided by @Amila Senadheera. This case uses the iterations of the map function to conform the desired output object. Even ist working, the output array from the map function is not used.

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

    let data = {}
    content.map((contentInfo) => {
      let key = contentInfo.replace(/-img\d$/, "") 
      let imgName = contentInfo //Name of the Image
      data[key] = {
          Images: data[key] ? [...data[key].Images, imgName] : [imgName]  //Append New Image 2 Array Instead of OverWriting Them
      }
    })
console.log(data);

Comments

0

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
  if (data[key] == undefined) {
    data[key] = {
      Images: [imgName],
    };
  } else {
    data[key] = {
      Images: [...data[key].Images, imgName], //Append New Image 2 Array Instead of OverWriting Them
    };
  }
  console.log(data);
});

3 Comments

code does not run
I think you'd need to check if Images: data[key] exists to run your code. For the first iteration data[key] would not exist and you'd not be able to read data[key].Images
Yes, use an if condition to check if the value is undefined. I have updated the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.