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
If the objects on the array only have one key
and one value
, then you can use Object.entries() inside map() like this:
var arr = [];
arr.push({0:'Zero'});
arr.push({1:'One'});
let keys = arr.map(o => Object.entries(o)[0][0]);
let values = arr.map(o => Object.entries(o)[0][1]);
console.log(JSON.stringify(keys), JSON.stringify(values));
Otherwise, you could use the experimentals flat()
or flatMap()
like others have mentioned, or a version using reduce()
like this one:
var arr = [];
arr.push({0:'Zero'});
arr.push({1:'One', 2: 'two', 3: 'three'});
let keys = arr.reduce(
(acc, curr) => acc.concat(Object.keys(curr)),
[]
);
let values = arr.reduce(
(acc, curr) => acc.concat(Object.values(curr)),
[]
);
console.log(JSON.stringify(keys), JSON.stringify(values));
Here you're pushing Objects
inside array so you need to access them using index.
var arr = [];
arr.push({0:'Zero'})
arr.push({1:'One'})
let values = arr.map((e,index)=> arr[index][Object.keys(e)[0]])
console.log(values)
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 array Object.keys
will return the index of array which 0, 1 and so on
var arr = [];
arr.push({0:'Zero'})
arr.push({10:'One'})
console.log(Object.keys(arr))
Probably this is what you wanted to achieve. If this is the case than you need to use {} ( Object )
instead of [] ( Array )
var arr = {};
arr['0'] = 'Zero';
arr['1'] = 'One';
console.log(Object.keys(arr));
console.log(Object.values(arr))
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:
const arr = [];
arr.push({0: 'Zero'})
arr.push({1: 'One'})
console.log(arr.flatMap(Object.keys));
console.log(arr.flatMap(Object.values));
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:
const arr = [];
arr.push({0: 'Zero'});
arr.push({1: 'One'});
console.log(arr.reduce((acc, obj) => [...acc, Object.keys(obj).shift()], []));
console.log(arr.reduce((acc, obj) => [...acc, Object.values(obj).shift()], []));
It's because arr
is an array, not an object. You should use map
like so:
var arr = [];
arr.push({0: 'Zero'})
arr.push({1: 'One'})
console.log(arr.map(e => Object.keys(e)).flat(1));
console.log(arr.map(e => Object.values(e)).flat(1));
I used flat
to make the array flat, instead of it being nested.