Home > Blockchain >  How to convert one object to another object with different structure
How to convert one object to another object with different structure

Time:08-10

I have an object

const object1 = {
   75f649a2-0add-41df-a670-46bcd6150588: 6,
   990b503d-e322-42b1-9236-639a4daca6cb: 0,
   b1fd742c-f3b2-11ec-81e1-0242ac140005: 2
}

which I need to map somewhow into this structure:


 {
   "75f649a2-0add-41df-a670-46bcd6150588": {
     "maximal_offers_per_day": 6
      },
   "990b503d-e322-42b1-9236-639a4daca6cb": {
      "maximal_offers_per_day": 0
      },
   "990b503d-e322-42b1-9236-639a4daca6cb": {
      "maximal_offers_per_day": 2
      },
 }

What is the best way to do that?

CodePudding user response:

Just reduce over the entries

const object1 = {
   "75f649a2-0add-41df-a670-46bcd6150588": 6,
   "990b503d-e322-42b1-9236-639a4daca6cb": 0,
   "b1fd742c-f3b2-11ec-81e1-0242ac140005": 2
}

const object2 = Object.entries(object1).reduce((acc, [key, val]) => {
  acc[key] = {
    maximal_offers_per_day: val
  };
  return acc;
}, {});

console.log(object2);

CodePudding user response:

const object1 = {
   "75f649a2-0add-41df-a670-46bcd6150588": 6,
   "990b503d-e322-42b1-9236-639a4daca6cb": 0,
   "b1fd742c-f3b2-11ec-81e1-0242ac140005": 2
}

const object2 = Object.entries(object1).reduce((acc, [key, val]) => {
  acc[key] = {
    maximal_offers_per_day: val
  };
  return acc;
}, {});

console.log(object2);

  • Related