I
I
Iliana2020-05-21 22:16:18
JavaScript
Iliana, 2020-05-21 22:16:18

How to access a dynamic property of a JSON object and pass its value to an array?

Sending a request to the server, I get a response in the form {"Country":{"Service":{"cost":Cost,"count":Quantity}}}
For example:
{"0":{
"vk":{"cost" :3,"count":32}
"ok":{"cost":5.5,"count":455}}}
I need to get the cost and count values ​​for each service, the services are different.
I do not understand how to contact them if the names of the services are different.

To get data from an object like {"vk_0":73,"ok_0":188,"wa_0":32,"vi_0":173,"tg_0":254,"wb_0":208,"go_0":210} I
used the following code:

$.ajax({
        method: 'POST',
        url: 'getContentFromUrl.php', 
        data: {
           'ext_url': api_link,
        },
        success: function(data) {
            let new_data = JSON.parse(data);
            $.each(new_data, function (key, value){
                $('#first').find('span#'+key).text(value + ' шт');
            });
        },
        error:function() {
            console.log('Error');
        }
    });
})

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question