Convert array of array into array of object with custom keys- React

I am currently working on a array of array received from an endpoint and I want it to be converted into array of object. My array looks like bellow,

{
  "results": [
    [
      "ASIA",
      "INDIA",
      "2003",
      "Type 1",
      "Group 1",
      "Division 1"
    ],
    [
      "AFRICA",
      "Nigeria",
      "2004",
      "Type 2",
      "Group 2",
      "Division 2"
    ]
}

Code I have tried so far :

let finalArr = [];

  var objs = data.results.map((val) => {
    finalArr.push(Object.assign({}, val));
  });

console.log("Converted into Array of Object",finalArr)

The above code returns array of object with keys as 0,1,2,3 but ,I would like my array object to have custom keys and expected output is :

[
    {
      Region: "ASIA",
      Country: "INDIA",
      Year: "2004",
      Type: "Type 1",
      Group: "Group 1",
      Divison: "Division 1",
    },
    {
      Region: "AFRICA",
      Country: "Nigeria",
      Year: "2003",
      Type: "Type 2",
      Group: "Group 2",
      Divison: "Division 2",
    },
  ];

>Solution :

You can do it using the map function like this:

  const data = {
    results: [
      ["ASIA", "INDIA", "2003", "Type 1", "Group 1", "Division 1"],
      ["AFRICA", "Nigeria", "2004", "Type 2", "Group 2", "Division 2"]
    ]
  };
  const finalArr = data.results.map((el) => ({
    Region: el[0],
    Country: el[1],
    Year: el[2],
    Type: el[3],
    Group: el[4],
    Divison: el[5]
  }));
  console.log(finalArr);

or with custom keys:

  const customKeys = ["Region", "Country", "Year", "Type", "Group", "Division"];
  const data = {
    results: [
      ["ASIA", "INDIA", "2003", "Type 1", "Group 1", "Division 1"],
      ["AFRICA", "Nigeria", "2004", "Type 2", "Group 2", "Division 2"]
    ]
  };
  const finalArr = data.results.map((el) => {
    const obj = {};
    for (let i = 0; i < el.length; ++i) {
      obj[customKeys[i]] = el[i];
    }
    return obj;
  });
  console.log(finalArr);

Leave a Reply