Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return new JS object using previous object values

I have an object of objects (for example):

const previousMap = {123456: {title: 'Test 1', productID: 123456}, 234567: {title: 'Test 2', productID: 234567}}

and would like to return a new object, with each key as the titles of the previous object, and its values as the sku (which also happen to be the keys of the last object-- but I would rather use the .sku attribute).

For example:

const newMap = {'Test 1' : 123456, 'Test 2': 234567}

I have tried:

newMap = Object.entries(previousMap).map(([key, value]) => ({[value.title] : value.productID}))

but wind up getting an array of objects.

This is something that I feel as though I would normally be able to accomplish but my brain is really not working today. Any help = greatly appreciated :)

like image 579
TFT0764 Avatar asked Mar 18 '26 19:03

TFT0764


1 Answers

Another possible solution:
Changing the map to return an array of key and value [k,v] and then calling Object.fromEntries on it.

const previousMap = {
  123456: {
    title: 'Test 1',
    productID: 123456
  },
  234567: {
    title: 'Test 2',
    productID: 234567
  }
}

let newMap = Object.fromEntries(
  Object.entries(previousMap)
  .map(([key, value]) => [value.title, value.productID])
);

console.log(newMap)
like image 102
cmgchess Avatar answered Mar 21 '26 09:03

cmgchess