Lafoune
Lafoune

Reputation: 476

how to access specific data in json in javascript

I'm trying to access specific data from json array. and i'm using dynamic dropdown.

So in my case i want get all names from the json and plot it on option.

here is the Json we're accessing..

[
 {
    "id": 1,
    "name": "john" 
    "age": 23,
    "city": "New York" 
 },
 {
    "id": 2,
    "name": "Donald" 
    "age": 34,
    "city": "London" 
 },
 {
    "id": 3,
    "name": "k'nan" 
    "age": 27,
    "city": "Paris" 
 },
 {
    "id": 1,
    "name": "jose" 
    "age": 29,
    "city": "lesbon" 
 },
]

script

$.each(data, function(key,vlaue ){
          $('select[name="bus_number"]').append('<option value="'+ key +'">'+ value +'</option>');
 });

and again i want to access only all names and plot it on options. i did this and it's not working and may be you guys will tell me a better way.

Upvotes: 0

Views: 47

Answers (2)

Yoav Kadosh
Yoav Kadosh

Reputation: 5155

I'm assuming that you are trying to create a dropdown where the options' labels are the names in the data and the options' values are the corresponding ids.

data.forEach(({id, name}) => {
    $('select[name="bus_number"]').append(`<option value="${id}">${name}</option>`);
});

Notice that I use JavaSctipt's native forEach instead of jQuery's (no need for that anymore), and I'm also using Object Desctructuring and String Literals which make your code easier to read.

Here's a fiddle.

Upvotes: 1

bassxzero
bassxzero

Reputation: 5041

Brb to explain soon.

Jquery:

var data = [
 {
    "id": 1,
    "name": "john", 
    "age": 23,
    "city": "New York" 
 },
 {
    "id": 2,
    "name": "Donald", 
    "age": 34,
    "city": "London" 
 },
 {
    "id": 3,
    "name": "k'nan", 
    "age": 27,
    "city": "Paris" 
 },
 {
    "id": 1,
    "name": "jose", 
    "age": 29,
    "city": "lesbon" 
 },
];

$.each( data, function( index, object ) {
  $('select[name="bus_number"]').append('<option value="'+ object['id'] +'">'+ object['name'] +'</option>');
});

Upvotes: 1

Related Questions