-1

I currently experience the problem when i want to deserialize json. I dont know how to do this with unknown keys

[
    {
        "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
        ]
    }
]

How would i go about this when i want

1. 84.200.222.4
- 0.022

2. 84.200.230.82
- 1,315

3. 80.156.160.161
- 0.874

4 72.14.217.108
- 0.662

Etc.. I'm currently not sure on how to loop through unknown keys is that possible?

Select
  • 93
  • 1
  • 11

4 Answers4

5

Simply iterate through the array, and use Object.keys(), which returns an array of all the object's properties.

arr.forEach(obj => {
    console.log(Object.keys(obj)[0]);
})
frozen
  • 2,114
  • 14
  • 33
2

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.

InfinityCounter
  • 374
  • 2
  • 4
  • 14
2

Here's a quick way to process it:

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]}`);
});
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
1

Use:

var parsed = JSON.parse(data);

this will return a javascript object/array.

then do

var result = parsed[0].keys.map(key => { /** do whatever **/});
ThomasK
  • 300
  • 1
  • 8