0

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"}]

3 Answers 3

2

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)

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

1 Comment

Etsuko thanks, this answer is not hardcoded and perfect
1
let result =[]
arr2.forEach(element => {
    let data = `{${arr1[0]} : ${element[0]}, ${arr1[1]} : ${element[1]}, ${arr1[2]} : ${element[2]} }`
    result.push(data)
});

Comments

1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.