Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have an object that has multiple arrays that looks something like this.

JavaScript
let obj = { 
	links: ["https://somelink.com/image.jpg", "https://somelink.com/image2.jpg"],
	IDs: ["yCmj", "4q1K"],
}


I want to make it so that it's turned into an array of objects. Like the following.

JavaScript
let newObj = {
   templates: [
      {id:"yCmj", link: "https://somelink.com/image.jpg"}, 
      {id:"4q1K", link: "https://somelink.com/image2.jpg"}
   ] 
}


What I have tried:

I tried mapping the object values to a new array but the second map overwrites the whole array.

JavaScript
let templates = obj.templateIDs.map((id) => ({id}))
templates = obj.thumbnailLinks.map((thumbnailLink) => ({thumbnailLink}))

let newObj = templates
Posted
Updated 14-Apr-21 5:01am
v2

If you don't want to use a loop, then this should work:
JavaScript
let newObj = {
	templates: obj.IDs.map((id, index) => ({ id, link: obj.links[index] }))
};
Demo[^]
 
Share this answer
 
Couldn't you just keep-it-simple and loop through the arrays and construct the new array as you go through them in parallel ?

Don't over complicate your code: and array is an array. It is rare that the simplest solution isn't the best.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900