skip to Main Content

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?

2

Answers


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

    Login or Signup to reply.
  2. 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]}));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search