Foreach JSON with random keys

This question already has an answer here:

  • How do I loop through or enumerate a JavaScript object? 29 answers

  • 只需遍历数组,并使用Object.keys() ,它将返回所有对象属性的数组。

    arr.forEach(obj => {
        console.log(Object.keys(obj)[0]);
    })
    

    以下是处理它的一种快速方法:

    var array = [{
      "84.200.222.4": [0.022]
    }, {
      "84.200.230.82": [1.315]
    }, {
      "80.156.160.161": [0.874]
    }, {
      "72.14.217.108": [0.662]
    }, {
      "108.170.251.193": [0.638]
    }, {
      "216.239.54.61": [0.64]
    }, {
      "172.217.23.131": [0.564]
    }];
    
    array.forEach((object, index) => {
      var ip = Object.keys(object).pop();
      console.log(`${index + 1}. ${ip}n- ${object[ip]}`);
    });

    I didn't test this but It should work.

    Firstly it's an array so you want to loop over that. Then although the object keys vary, you can use object.keys to get the keys of an object, or just iterate over the object. So your code would look like so

    function printValues(arr)
    {
        var arrayLength = arr.length;
        for (var i = 0; i < arrayLength; i++) 
        {
            let obj = arr[i];
            for (var key in obj) {
                x = obj[key];
                alert(x);
            }
        }
    }
    

    This could be optimized down to a single line but I made it as simple as possible for you to understand.

    链接地址: http://www.djcxy.com/p/28836.html

    上一篇: Javascript获取Object的所有属性

    下一篇: 带有随机密钥的Foreach JSON