teestunna
teestunna

Reputation: 217

Mapping two arrays to get an array of object

I need help in getting elements in one array and mapping it to elements in an array of arrays to get an array of object in key value pairs For example:

let arr1 = ["ProjectUniqueID","CompanyUniqueID","ClientProjectID"];
let arr2 = [["20-2867451","2","20-2867451",],
            ["05-3134339","1","05-3134339"],
            ["80-8424593","3","80-8424593",],
            ["18-2895279","3","18-2895279"]
            ]



result = [{ ProjectUniqueID: "20-2867451", CompanyUniqueID: "2", ClientProjectID: "20-2867451"},
          { ProjectUniqueID: "05-3134339", CompanyUniqueID: "1", ClientProjectID: "05-3134339"},
          { ProjectUniqueID: "80-8424593", CompanyUniqueID: "3", ClientProjectID: "80-8424593"},
          { ProjectUniqueID: "18-2895279", CompanyUniqueID: "3", ClientProjectID: "18-2895279"}]

Upvotes: 0

Views: 2491

Answers (3)

BTSM
BTSM

Reputation: 1663

I think you can use Object.fromEntries function like this.

let arr1 = ["ProjectUniqueID","CompanyUniqueID","ClientProjectID"];
let arr2 = [["20-2867451","2","20-2867451",],
            ["05-3134339","1","05-3134339"],
            ["80-8424593","3","80-8424593",],
            ["18-2895279","3","18-2895279"]
            ]
let arrObj = [];
arr2.map((element)=>{
  let item = Object.fromEntries(
    arr1.map((el, index) => [el, element[index]])
  );
  arrObj.push(item);
  }
)
console.log(arrObj)

Upvotes: 2

ZeroLiam
ZeroLiam

Reputation: 212

Loop in arr2, make a temp object, and try to map the each entry of arr1 as the key and each element of the current position on the arr2 as the values for those keys. Finally, push the temp object into an array. For example:

let arrObj = [];
for(let entry of arr2) {
    let obj = {
            [arr1[0]]: entry[0],
            [arr1[1]]: entry[1],
            [arr1[2]]: entry[2],
    };
    arrObj.push(obj);
}

This might be a problem if you have a lot of data to loop in

Upvotes: 1

veysiisik
veysiisik

Reputation: 157

let result =[]
arr2.forEach(element => {
    let data = `{${arr1[0]} : ${element[0]}, ${arr1[1]} : ${element[1]}, ${arr1[2]} : ${element[2]} }`
    result.push(data)
});

Upvotes: 1

Related Questions