实际输出:
[["Name","Age","Location","Gender"],["Mary",28,"KY","F"],["Jonathan",34,"NJ","M"],["Kevin",31,"CA","M"]]
预期输出 :
[
{
"Name":"Mary",
"Age":28,
"Location":"KY" ,
"Gender":"F"
},
{
"Name":"Jonathan",
"Age":34,
"Location":"NJ",
"Gender":"M"
},
{
"Name":"Kevin",
"Age":31,
"Location":"CA",
"Gender":"M"
}
]
请帮我解决这个问题。这样我就可以在表中迭代。
提前致谢
试试这个:
const input = [["Name", "Age", "Location", "Gender"], ["Mary", 28, "KY", "F"], ["Jonathan", 34, "NJ", "M"], ["Kevin", 31, "CA", "M"]];
const keys = input[0];
const output = input.slice(1).map(entry => {
const retVal = {};
keys.forEach((key, index) => {
retVal[key] = entry[index];
});
return retVal;
});
console.log(output);
从值中解构键。映射值数组 (vals
(,并使用Object.fromEntries()
通过映射每个值子数组 (varr
( 来创建对象,并与相应的键组合以创建 [键,值] 条目数组。
从值和键创建对象:
const objecttify = ([keys, ...vals]) => // destructure the keys and an array of values
vals.map(varr => // map the values
Object.fromEntries( // convert the entries to an object
varr.map((v, i) => [keys[i], v]) // create the entries by combining a value with it's respective key
)
)
const arr = [["Name","Age","Location","Gender"],["Mary",28,"KY","F"],["Jonathan",34,"NJ","M"],["Kevin",31,"CA","M"]]
const result = objecttify(arr)
console.log(result)