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?
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));
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);
You can use Object.keys to extract all property names:
var arr=[];
Object.keys(obj).forEach(function(key){
arr.push([key, obj[key]]);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.