Reputation: 84
I have this code in my javascript file:
var items = {
first: 'Item 1',
second: 'Item 2',
third: 'Item 3'
};
var arr = Array.prototype.slice.call(items);
console.log(arr.length);
I want to convert an object into an array. My question is, when the object was converted into array, why does javascript return 0
when the object already has properties? I hope someone could help me and if anyone wouldn't mind, I want it to be corrected without using jQuery.
Upvotes: 0
Views: 1785
Reputation: 1
You can use Object.entries()
to create an array of arrays of properties, values from original object or an array of objects reflecting properties, values of original object.
The
Object.entries()
method returns an array of a given object's own enumerable property[key, value]
pairs, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var items = {
first: 'Item 1',
second: 'Item 2',
third: 'Item 3'
};
var arr = Object.entries(items);
console.log(arr);
var arr1 = Object.entries(items)
.map((value, index) => {
return {[value.shift()]: value.pop()}
});
console.log(arr1);
Upvotes: 2