Home > database >  How to assign a Singular Keys Array to Multiple Nested Value Arrays
How to assign a Singular Keys Array to Multiple Nested Value Arrays

Time:12-10

I want to assign the keys in (arr1) to the strings in each nested array in (arr2). I am only a month into learning javascript, and have been stuck on this problem and have been trying to find a working method.

Given the following arrays:

 arr1 = ["Date","Start","High","Low","End","AdjEnd","Amount"] //KEYS I WANT TO ASSIGN TO EACH STRING
 arr2 = [["1997-06-01","75","80","65","78","79","3000"],
         ["1997-06-02","70","75","60","73","74","3300"],
         ["1997-06-03","80","85","70","83","84","3800"],...] // THERE ARE 10,000  OF THESE STRINGS

I want the output to create objects that look like this:

var newArray = [
{
  Date: "1997-06-01",
  Start: "75",
  High: "80",
  Low: "65",
  End: "78",
  AdjEnd: "79",
  Amount: "3000"
}

{
  Date: "1997-06-02",
  Start: "70",
  High: "75",
  Low: "60",
  End: "73",
  AdjEnd: "74",
  Amount: "3300"
}

{
  Date: "1997-06-03",
  Start: "80",
  High: "85",
  Low: "70",
  End: "83",
  AdjEnd: "84",
  Amount: "3800"
}

//continuing through all nested arrays

I can get the format I am looking for with this code, but it is not practical for thousands of arrays.

var result1 = {};
arr1.forEach((key, i) => result1[key] = arr2[0][i]);

var result2 = {};
arr1.forEach((key, i) => result2[key] = arr2[1][i]);


// result3 and so on

var allresult = [result1, result2] //add result3 and so on
console.log(allresult);

CodePudding user response:

const arr1 = ["Date", "Start", "High", "Low", "End", "AdjEnd", "Amount"];
const arr2 = [
    ["1997-06-01", "75", "80", "65", "78", "79", "3000"],
    ["1997-06-02", "70", "75", "60", "73", "74", "3300"],
    ["1997-06-03", "80", "85", "70", "83", "84", "3800"]
];

const result = arr2.map(a => {
    return a.reduce((p, c, i) => ({ ...p, [arr1[i]]: c }), {});
})

console.log(result);

CodePudding user response:

Here is a straight forward approach using a .map() and a .forEach():

 const arr1 = ["Date","Start","High","Low","End","AdjEnd","Amount"];
 const arr2 = [
   ["1997-06-01","75","80","65","78","79","3000"],
   ["1997-06-02","70","75","60","73","74","3300"],
   ["1997-06-03","80","85","70","83","84","3800"]
];
let result = arr2.map(row => {
  let obj = {};
  arr1.forEach((name, idx) => {
    obj[name] = row[idx];
  });
  return obj;
});
console.log(result);

  • Related