0

I have an object that has multiple arrays that looks something like this.

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.

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.

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

let newObj = templates

4 Answers 4

1

The easiest way to accomplish this would be to pick either obj.links or obj.IDs and map their values to an object and use the index to locate the corresponding parallel value.

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

const newObj = {
  templates: obj.links.map((link, index) => (id => ({ id, link }))(obj.IDs[index]))
};

console.log(newObj);
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

1 Comment

I completely forgot that map accepts callbacks and also has the index parameter... that's much better.
1

This operation is typically called "zipping" 2 arrays:

const zip = (a,b, zipper) => {
  if(a.length != b.length)
    throw "arrays must be the same length";
    
  return a.map( (v,i) => zipper(v,b[i]))
}

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

const newObj = {
  templates: zip(obj.links, obj.IDs, (link,id) => ({link,id}))
}

console.log(newObj);

Comments

0

You can simply use map.

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

const newObj = {
  templates: obj.links.map((link, i) => ({ link, id: obj.IDs[i] })),
};

console.log(newObj);

Comments

-1
let obj = { 
    links: ["https://somelink.com/image.jpg", "https://somelink.com/image2.jpg","https://somelink.com/image2.jpg"],
    IDs: ["yCmj", "4q1K","34er"],
}
let propsKey = Object.keys(obj)
let finalArr =  obj.links.map( ()=> {
         return {}
})

propsKey.forEach( (prop) => {
  obj[prop].forEach( (v,i)=>finalArr[i][prop] = v  )
})
 

console.log(finalArr)  
 

Comments

Your Answer

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