我有以下对象需要转换为稍微不同的格式。我非常确定我可以使用节点本地map
函数来翻译它。例如
var animals = [
[ 'cats', 1726, 1143, 10, 105, 2382, 0 ],
[ 'dogs', 640, 0, 0, 0, 0, 0 ],
[ 'cows' 13509, 0, 3, 1, 196939, 19 ],
[ 'sheep', 1573, 1084, 10, 105, 2266, 0 ]
]

采用以下格式:
new_animals = [{
name: 'cats',
data: [1726, 1143, 10, 105, 2382, 0]
}, {
name: 'dogs',
data: [640, 0, 0, 0, 0, 0]
}, {
name: 'cows',
data: [13509, 0, 3, 1, 196939, 19]
},
{
name: 'sheep',
data: [1573, 1084, 10, 105, 2266, 0]
}]

答案 0 :(得分:1)
使用ES2015功能:
const newAnimals = animals.map(([name, ...data]) => ({ name, data }));
没有ES2015功能:
var newAnimals = animals.map(function (animal) {
return {
name: animal[0],
data: animal.slice(1)
};
});
答案 1 :(得分:0)
其实非常简单:
var animals = [
['cats', 1726, 1143, 10, 105, 2382, 0],
['dogs', 640, 0, 0, 0, 0, 0],
['cows', 13509, 0, 3, 1, 196939, 19],
['sheep', 1573, 1084, 10, 105, 2266, 0]
];
console.log(animals.map(([name, ...data]) => ({name, data})));
替代方案,如果您的节点版本不支持lambdas:
animals.map(function (animal) {
return {
name: animal.shift(),
data: animal
};
});