转换的最佳方式是什么,
{
"columns":[
"name",
"color"
],
"values":[
[
"lion",
"yellow"
],
[
"crow",
"black"
]
]
}
到
{
"data":[
{
"name":"lion",
"color":"yellow"
},
{
"name":"crow",
"color":"black"
}
]
}
而不是循环,有没有可用的功能?我可以通过extend()吗?
来实现它答案 0 :(得分:4)
您可以将Object.assign
与spread syntax ...
用于部分。
var object = { columns: ["name", "color"], values: [["lion", "yellow"], ["crow", "black"]] },
result = { data: object.values.map(v => Object.assign(...object.columns.map((c, i) => ({[c]: v[i]})))) };
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)
你可以用map和reduce的组合来做。减少原始列数组将允许代码使用任意数量的列,它将通过索引获取相应的值:
const result = {data: data.values.map(el => {
return data.columns.reduce((prev, curr, index) => {
prev[curr] = el[index]
return prev
}, {})
})}
查看下面的演示。
const data = {
"columns":[
"name",
"color"
],
"values":[
[
"lion",
"yellow"
],
[
"crow",
"black"
]
]
}
const result = {data: data.values.map(el => {
return data.columns.reduce((prev, curr, index) => {
prev[curr] = el[index]
return prev
}, {})
})}
console.log(result)

答案 2 :(得分:2)
您可以使用解构赋值,spread元素获取.columns
数组的值; for..of
循环通过迭代原始对象的.columns
属性将data
数组的计算属性作为字符串分配为.values
数组中对象的属性,将每个数组的值指定为值创建对象
let obj = {
"columns":[
"name",
"color"
],
"values":[
[
"lion",
"yellow"
],
[
"crow",
"black"
]
]
}
let [res, key, value] = [{data:Array()}, ...obj.columns];
for (let [a, b] of [...obj.values]) res.data.push({[key]:a, [value]:b});
console.log(res);