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));