How to return the name of an existing object in a JSON

Asked

Viewed 217 times

3

I have the JSON file below:

{
  "uid1":{
    "start_time":"20140815",
    "name":"name 1"
    },
  "uid2":{
    "start_time":"20141229",
    "name":"name 2"
    },
  "uid3":{
    "start_time":"20140809",
    "name":"name 3"
    },
  "uid4":{
    "start_time":"20140830",
    "name":"name 4"
    },
  "uid5":{
    "start_time":"20140920",
    "name":"name 5"
    }
}

I need not only return the values within each "uid" but also the "name" of "uid" where the result is something like this:

uid1,20140815,name 1

2 answers

2


You can do something like this:

var obj = {
    "uid1": {
        "start_time": "20140815",
            "name": "name 1"
    },
        "uid2": {
        "start_time": "20141229",
            "name": "name 2"
    },
        "uid3": {
        "start_time": "20140809",
            "name": "name 3"
    },
        "uid4": {
        "start_time": "20140830",
            "name": "name 4"
    },
        "uid5": {
        "start_time": "20140920",
            "name": "name 5"
    }
};

// Montagem dos resultados.

var resultado = [];

for (var prop in obj) {
    resultado.push(prop + ',' + obj[prop].start_time + ',' + obj[prop].name);
}

// Exibição dos resultados.

for (var i = 0; i < resultado.length; i++) {
    alert(resultado[i]);
}
  • perfect blemish,

1

You can do it this way

Jquery

var json = {
  "uid1":{
    "start_time":"20140815",
    "name":"name 1"
    },
  "uid2":{
    "start_time":"20141229",
    "name":"name 2"
    },
  "uid3":{
    "start_time":"20140809",
    "name":"name 3"
    },
  "uid4":{
    "start_time":"20140830",
    "name":"name 4"
    },
  "uid5":{
    "start_time":"20140920",
    "name":"name 5"
    }
};

$(function(){
    $.each(json, function(i, v){
       $('ul').append('<li>'+ i + ', ' + v.start_time + ', ' + v.name +'</li>'); 
    });
});

The above example populates an element <ul>, use to adapt your application.

You can also see this DEMO with the example working

Browser other questions tagged

You are not signed in. Login or sign up in order to post.