1

i have following json data

from this i have name 'iPhone 4s'.

but while inputing the name 'iPhone 4s' how can i get the corresponding values of host and target.am using javascript

{
    devices: [
        {
            name: 'iPhone 4s',
            host: '3.175: 375',
            target: '137fc82506eb75431ec96fdd'
        },
        {
            name: 'iPhone 5s',
            host: '19:7265',
            target: 'ea4c19957bbba6980db0f7'
        }
    ]
}
caramba
  • 21,963
  • 19
  • 86
  • 127
divz
  • 7,847
  • 23
  • 55
  • 78
  • 1
    Here you can find number of options: http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects for finding an object in array by property. – dfsq Dec 05 '14 at 08:09

2 Answers2

1

Javascript provide JSON.parse(); for parsing json data.

You can save your response in variable.

var response=JSON.parse(data);

Then use the all value from it's key.

var name = response.devices[0].name;
var host = response.devices[0].host;
var target = response.devices[0].target;

These code only get the 1st array element values. Using for loop you can get get all values from devices array.

Nayan Dabhi
  • 986
  • 9
  • 20
1
var data = JSON.parse(response);

data.devices.forEach(function(device) {
    if(device.name === 'iPhone 4s') {
        console.log(device.name, device.host, device.target);
    }
});

// 'iPhone 4s', '3.175: 375', '137fc82506eb75431ec96fdd'
Leo
  • 13,428
  • 5
  • 43
  • 61