0

I want to create a javascript object such as below :

{
   {
    "Image" :  img_src,
    "Text" :   text
    },

}

I have two arrays

img_src = [ value1, value2, value3 ....... ]
text = [ text1, text2, text3 .......]

I want to map the values of these arrays in that object such that values of img_src is placed next to key "Image" and values of text is places next to key "Text" in the following manner:

{
   {
     "Image" : value1,
     "Text" : text1
   },
  {
     "Image" : value2,
     "Text" : text2
   },
  {
     "Image" : value3,
     "Text" : text3
   } 
}

and so on. I tried reading javascript documentation and tried all sort of things but I am unable to come up with a solution. Could someone kindly explain how can I achieve this?

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • you can use map and its index https://stackoverflow.com/questions/75992506/merge-array-objects-of-different-values-in-a-new-object/75992552#75992552 – cmgchess Apr 26 '23 at 20:34
  • Does this answer your question? [How to create an array of objects from multiple arrays](https://stackoverflow.com/questions/40539591/how-to-create-an-array-of-objects-from-multiple-arrays) – pilchard Apr 26 '23 at 20:57

2 Answers2

0

Either use a for loop to iterate over both arrays and construct an object from them or use the .map() function.

Egge
  • 256
  • 2
  • 7
0

I believe you want an array of objects as the output. If so, you can map over one of the arrays, ex. img_src, and use a combination of items and indexes to generate each combined object.

let combined = img_src.map((img, index) => ({Image: img, Text: text[index]}));
soundslikeodd
  • 1,078
  • 3
  • 19
  • 32