I have a problem with my code it has a running error I am trying to convert an object to an array list. In my code, I was trying to build an array inside an array! I was expecting to have a return value as the following:
[['name', 'Holly'], ['age' , 35], ['role', 'producer' ],
['species', 'canine'], ['name', 'Bowser'], ['weight', 45]]
I will appreciate any help or advice thanks.
var obj1 = {
name: 'Holly',
age: 35,
role: 'producer'
};
var obj2 = {
species: 'canine',
name: 'Bowser',
weight: '45'
};
function convertObjectToList(obj) {
var arrayExt = []; // declare my external array container
var arrayInt = []; // declare my internal arrays container
var objKeys = Object.getOwnPropertyNames(obj); // returns all properties (enumerable or not) found directly upon a given object.
for (var k in obj) {
if (var i = 0; i < objKeys.length; i++);
arrayInt = [];
arrayInt.push(obj(objKeys[k]));
arrayExt.push(arrayInt);
console.log(arrayExt);
}
}
convertObjectToList(obj);
You can just use a use a combination of Object.keys
, Array.map
, and Array.concat
function toArray(obj) {
return Object.keys(obj).map(k => [k, obj[k]]);
}
var obj1 = { name: 'Holly', age: 35, role: 'producer' };
var obj2 = { species: 'canine', name: 'Bowser', weight: '45'};
console.log(toArray(obj1).concat(toArray(obj2)))
In general, you should avoid for...in
loops. There are many better alternatives now.
Collected from the Internet
Please contact javaer1[email protected] to delete if infringement.
Comments