-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

2
  • You're already using Object.keys() - why doesn't that work? Commented Feb 7, 2019 at 12:03
  • 1
    Use Object.keys(obj) for keys and Object.value(obj) for value. Commented Feb 7, 2019 at 12:05

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.