Javascript iterate Json Array to get values

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

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

提交回复
热议问题