JSON数据当前看起来像这个字符串:
("ID">,"Name","Age"],["212","David"38"]
我想让它看起来像这样:
{"ID"212","Name":"David","Age":"38"}
事先感谢您的帮助
我找到了这段代码,它解决了大部分问题
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);
您可以通过以下步骤完成:
- 从数组 中提取键和值
- 将它们压缩到键匹配值
- 使用object . fromentries创建对象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);
假设让jsonVal =[["ID","Name","Age"],["212","David"38"],["212","David"38"]]第0个索引将包含键,其余为数据
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将有一个你需要的对象数组