0

I have an array object here:

var obj = { name: 'Chris', age: 25, hobby: 'programming' }; 

I need a function that will convert an object literal into an array of arrays even without knowing the key or the value like this:

[['name', 'Chris'], ['age', 25], ['hobby', 'programming']] 

So I created a function to do that. However I am not sure where to start to enable me to merge them.

function convert(obj) { var array = []; } convert(obj); 

Any help?

3

3 Answers 3

2

using Object.keys() and Array#map()

var obj = { name: 'Chris', age: 25, hobby: 'programming' }; function convert(obj) { return Object.keys(obj).map(k => [k, obj[k]]); } console.log(convert(obj));

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

Comments

0

You can do this:
1. Iterate through the object
2. Push the key and value in to array and then puh that array into answer array

 var obj = { name: 'Chris', age: 25, hobby: 'programming' }; var ans = []; for(var i in obj) { ans.push([i, obj[i]]); } console.log(ans);

Comments

0

You can use Object.keys to extract all property names:

var arr=[]; Object.keys(obj).forEach(function(key){ arr.push([key, obj[key]]); }) 

Comments