I have a below JavaScript
var arr = [];
arr.push({0:'Zero'});
arr.push({1:'One'});
console.log(Object.keys(arr));
console.log(Object.values(arr)); //Not getting expected result
I want to print keys and values separately, could able to fetch keys but not able to get values.
Here you're pushing
Objects
inside array so you need to access them using index.On side note: Both of your console is not working change the keys to anything else than
0 and 1
and see the output. In case of arrayObject.keys
will return the index of array which0, 1 and so on
Probably this is what you wanted to achieve. If this is the case than you need to use
{} ( Object )
instead of[] ( Array )
You can use
.flatMap
to get the keys/values from your objects (in the form of an array) and then flatten the array into your result:However, please note,
.flatMap
is has limited browser support and so it may not work in all browsers. Instead, if you cannot use.flatMap
and want a more stable solution you can use.reduce
:It's because
arr
is an array, not an object. You should usemap
like so:I used
flat
to make the array flat, instead of it being nested.If the objects on the array only have one
key
and onevalue
, then you can use Object.entries() inside map() like this:Otherwise, you could use the experimentals
flat()
orflatMap()
like others have mentioned, or a version usingreduce()
like this one: