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);
CodePudding user response:
You could do that with following steps:
- extract keys and values from array
- zip them to key match value
- 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);
CodePudding user response:
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