Javascript iterate Json Array to get values

前端 未结 4 1969
广开言路
广开言路 2021-01-16 05:55

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          


        
4条回答
  •  [愿得一人]
    2021-01-16 06:26

    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.

提交回复
热议问题