这是我的代码
var inputData = [{
name: 'Nick',
achievements: 158,
points: 14730
}, {
name: 'Jordan',
achievements: '175',
points: '16375'
}, {
name: 'Ramon',
achievements: '55',
points: '2025'
}];
var outputData = inputData.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
});
console.log(JSON.stringify(outputData));
结果为
[["Nick",158,14730],
["Jordan","175","16375"],
["Ramon","55","2025"]]
所需的输出
[["name", "achievements", "points"],
["Nick", "158", "14730"],
["Jordan", "175", "16375"],
["Ramon", "55", "2025"]]
基本上,我需要这种格式的数据来生成CSV。所以我将对象数组转换为数组数组。数组数组的第一行将包含键,而下一行将包含值。
我不想使用Lodash或Jquery。 Iam在Plain Vanilla JS中寻找解决方案
答案 0 :(得分:1)
简单地:
const outputData = [Object.keys(inputData[0]), ...inputData.map(Object.values)];
不过,您需要进行一些.length
检查。如果对象的形状不同,就会得到一些奇怪的结果。
答案 1 :(得分:0)
var inputData = [{
name: 'Nick',
achievements: 158,
points: 14730
}, {
name: 'Jordan',
achievements: '175',
points: '16375'
}, {
name: 'Ramon',
achievements: '55',
points: '2025'
}];
var outputData = inputData.reduce((acc,obj,i) => {
if(i == 0) acc.push(Object.keys(obj));
acc.push(Object.values(obj));
return acc;
},[]);
console.log(JSON.stringify(outputData));
答案 2 :(得分:0)
请使用以下代码-
var inputData = [{
name: 'Nick',
achievements: 158,
points: 14730
}, {
name: 'Jordan',
achievements: '175',
points: '16375'
}, {
name: 'Ramon',
achievements: '55',
points: '2025'
}];
var outputData = inputData.map(function(obj) {
return Object.keys(obj).map(function(key) {
return obj[key];
});
});
outputData.unshift(Object.keys(inputData[0]))
console.log(JSON.stringify(outputData));
仅添加outputData.unshift(Object.keys(inputData[0]))
,并删除现有代码中的sort()
方法。