Home > Mobile >  How to create a new objects of array by using object values in JavaScript
How to create a new objects of array by using object values in JavaScript

Time:12-09

I have two objects.

let obj1={"1":"Func P1","2":"Geo P2","3":"Calc P1","4":"Calc P2"}

let obj2={"1":"11","2":"44","3":"66","4":"88"}

I'd like to use values to create the following:

[{ myX: "Func P1", myY: 11 }, { myX: "Geo P2", myY: 44 },{ myX: "Calc P1", myY: 66},{myX: "Calc P2", myY: 88 }]

Is it possible to do it?

I tried this so far:


let combined = [];
      for (const [key1, value1] of Object.entries(obj1)) {
        for (const [key2, value2] of Object.entries(ojb2)) {
          combined.push({ myX: value1, myY: value2 });
        }
      }

CodePudding user response:

You can easily achieve the result using Object.keys and map

I've used to convert it to Number type, you can also use parseInt or Number also

 obj2[key]

let obj1 = { "1": "Func P1", "2": "Geo P2", "3": "Calc P1", "4": "Calc P2" };

let obj2 = { "1": "11", "2": "44", "3": "66", "4": "88" };

const result = Object.keys(obj1).map((key, index) => ({
  myX: obj1[key],
  myY:  obj2[key],
}));
console.log(result);

  • Related