Javascript iterate Json Array to get values

前端 未结 4 1861
广开言路
广开言路 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:11

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

提交回复
热议问题