我有这种格式的数组
0:["Emp Code", "Reportee Name", "Product", "Target", "Achievement","percentage"]
1:["1000001", "Harry", "Product A ", "116", "110", "94.82758621"]
2:["1000001", "Harry", "Product B", "94", "100", "106.3829787"]
3:["1000001", "Peter", "Product A ", "105", "104", "99.04761905"]
4:["1000001", "Peter", "Product B", "114", "110", "96.49122807"]
想要这样
[
"Emp Code":{
"1000001",
"Harry",
"Product A ",
"116",
"110",
"94.82758621"
},
"Reportee Name":{
"1000001",
"Harry",
"Product B ",
"94",
"100",
"106.3829787"
},
....
]
答案 0 :(得分:1)
假设您要使用数组中的第一项作为键,并且要使用该位置的数据作为键的值:
const input = [
["Emp Code", "Reportee Name", "Product", "Target", "Achievement","percentage"],
["1000001", "Harry", "Product A ", "116", "110", "94.82758621"],
["1000001", "Harry", "Product B", "94", "100", "106.3829787"],
["1000001", "Peter", "Product A ", "105", "104", "99.04761905"],
["1000001", "Peter", "Product B", "114", "110", "96.49122807"],
]
const getDataAtPosition = (data, i) => data.map(item => item[i])
const transform = data => data[0].reduce((prev, curr, i) => {
const thisDataWithTitle = getDataAtPosition(data, i);
const dataToUse = thisDataWithTitle.slice(1, thisDataWithTitle.length);
prev[curr] = dataToUse;
return prev;
}, {})
const test = transform(input)
console.dir(test)
答案 1 :(得分:0)
假设您想要一个对象数组,第一个数组作为键,后面的作为值,则可以通过将第一行作为键来映射切片的值。
var array = [["Emp Code", "Reportee Name", "Product", "Target", "Achievement", "percentage"], ["1000001", "Harry", "Product A ", "116", "110", "94.82758621"], ["1000001", "Harry", "Product B", "94", "100", "106.3829787"], ["1000001", "Peter", "Product A ", "105", "104", "99.04761905"], ["1000001", "Peter", "Product B", "114", "110", "96.49122807"]],
[keys, ...data] = array,
result = data.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }