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?
-
you can use map and its index stackoverflow.com/questions/75992506/…cmgchess– cmgchess2023年04月26日 20:34:52 +00:00Commented Apr 26, 2023 at 20:34
-
Does this answer your question? How to create an array of objects from multiple arrayspilchard– pilchard2023年04月26日 20:57:50 +00:00Commented Apr 26, 2023 at 20:57
2 Answers 2
Either use a for loop to iterate over both arrays and construct an object from them or use the .map() function.
Comments
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]}));
Comments
Explore related questions
See similar questions with these tags.