Parsing a list of lists and convert into a JSON object:

Viewed 507

Im trying to parse list of list to json object.I need the following output but my logic is not correct to get the actual output but instead getting im appending the key/value to the array

Input (Array):

var arraysample = 
    [
       [
          ["firstName", "Vasanth"],
          ["lastName", "Raja"], 
          ["age", 24], 
          ["role", "JSWizard"]
       ],
       [
          ["firstName", "Sri"], 
          ["lastName", "Devi"], 
          ["age", 28], 
          ["role", "Coder"]
       ]
    ];

Expected OUtput

[
   {firstName: “Vasanth”, lastName: “Raja”, age: 24, role: “JSWizard”},
   {firstName: “Sri”, lastName: “Devi”, age: 28, role: “Coder”}
]

My output:

[
   [ 'firstName', 'Vasanth' ],
   [ 'lastName', 'Raja' ],
   [ 'age', 24 ],
   [ 'role', 'JSWizard' ],
   firstName: 'Vasanth',
   lastName: 'Raja',
   age: 24,
   role: 'JSWizard'
],
[
   [ 'firstName', 'Sri' ],
   [ 'lastName', 'Devi' ],
   [ 'age', 28 ],
   [ 'role', 'Coder' ],
   firstName: 'Sri',
   lastName: 'Devi',
   age: 28,
   role: 'Coder'
]
]

MY Logic:

for(var i=0;i<arraysample.length;i++)
{
   for(var j=0;j<arraysample[i].length;j++)
   {
      arraysample[i][arraysample[i][j][0]]=arraysample[i][j][1];
   }
}
4 Answers

You can use Object.fromEntries() with Array.prototype.map():

var arraysample = [
  [
    ["firstName", "Vasanth"],
    ["lastName", "Raja"],
    ["age", 24],
    ["role", "JSWizard"]
  ],
  [
    ["firstName", "Sri"],
    ["lastName", "Devi"],
    ["age", 28],
    ["role", "Coder"]
  ]
];

var result = arraysample.map(Object.fromEntries);

console.log(result);

var result = [];

for(var i=0;i<arraysample.length;i++)
{  
 result[i] = {};
 for(var j=0;j<arraysample[i].length;j++)
  {
   result[i][arraysample[i][j][0]]=arraysample[i][j][1];
  }
}

A small Changes in your code.

let finalArray = []
let newArr = []
for (var i = 0; i < arraysample.length; i++) {
    for (var j = 0; j < arraysample[i].length; j++) {
        newArr[arraysample[i][j][0]] = arraysample[i][j][1]
    }
    finalArray.push(newArr)
}
console.log(finalArray)

But @MrGeek answer is more acceptable

console.log(
//take your array and read each element in it
  arraysample.map((array) => {
    let rObj = {};
//create an empty object to put your key name and value
    rObj[array[0][0]] = array[0][1];
//rObj[name] = value
    rObj[array[1][0]] = array[1][1];
    rObj[array[2][0]] = array[2][1];
    rObj[array[3][0]] = array[3][1];
    return rObj;
  })
);
Related