-3

This is my code

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));

This gives result as

 [["Nick",158,14730], 
 ["Jordan","175","16375"], 
 ["Ramon","55","2025"]]

Desired output

 [["name", "achievements", "points"],
 ["Nick", "158", "14730"],
 ["Jordan", "175", "16375"],
 ["Ramon", "55", "2025"]]

Basically i need my data in this format to generate CSV. So I am converting my array of objects to array of array. The first row of the array of array will contain the keys, while the next rows will contain the values.

I don't want to use Lodash or Jquery. Iam looking for a solution in Plain Vanilla JS

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
tommy123
  • 587
  • 1
  • 10
  • 28

3 Answers3

1

Simply:

const outputData = [Object.keys(inputData[0]), ...inputData.map(Object.values)];

though, you'd want some .length-check. And you'll get some strange results if the objects are of different shape.

Yoshi
  • 54,081
  • 14
  • 89
  • 103
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));
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
0

Please use below code -

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));

only outputData.unshift(Object.keys(inputData[0])) is added and sort() method is removed in your existing code.

Praveen Poonia
  • 745
  • 10
  • 18