0

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.

2 Answers 2

1

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>');
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.