1
votes

JSON data currently looks like this string:

["ID","Name","Age"],["212","David","38"]

And I would like for it to look like this:

{"ID":"212","Name":"David","Age":"38"}

Thanks for your help in advance

I found this code and it solves most of the issue

var columns = ["ID", "Name", "Age"];
var rows = ["212", "David", "38"];
var result =  rows.reduce(function(result, field, index) {
  result[columns[index]] = field;
  return result;
}, {})

console.log(result);
2
it's already usable JSON. that first string you posted is 100% valid JSON.I wrestled a bear once.
Sorry I'm kind of new to this, ok I see your point, but how could I make that JSON look like this {"ID":"212","Name":"David","Age":"38"}LuisFRN
It's already JSON, just like that.. Maybe if you posted some code it would be easier to see what your actual problem is.I wrestled a bear once.
I think he wants a JSON object structured like this csv is structured.Eric N
I Edited the question for it to make more senceLuisFRN

2 Answers

0
votes

You could do that with following steps:

  1. extract keys and values from array
  2. zip them to key match value
  3. use Object.fromEntries to create object key-value
let obj = [["ID","Name","Age"],["212","David","38"]]
let [keys, values] = obj;
let zipped = keys.map((key, i)=>[key, values[i]]);
let output = Object.fromEntries(zipped);
console.log(output);
0
votes

lets say let jsonVal = [["ID","Name","Age"],["212","David","38"], ["212","David","38"]] 0th index will have the keys and remaining is data

let newJsonVal = []  ​
 for (let i =1; i< jsonVal.length-1; i++) {
    ​let newObject ={}
     ​jsonVal[i].map((d,j) => { 
       ​newObject[jsonVal[0][j] = d;
      ​})
    newJsonVal.push(newObject)
 }

newJsonVal will have array of object as you need