How to access JSON database using javascript -


how can find "firstname" value "anna" , display "lastname" @ end using javascript? dummy example me understand how works.

var employees = [      {      "firstname":"john",      "lastname":"doe"      },       {      "firstname":"anna",      "lastname":"smith"      },      {      "firstname":"peter",      "lastname":"jones"      }  ];    document.getelementbyid("demo").innerhtml =  employees.firstname;
<p id="demo"></p>

you'd have iterate , check value, want:

for (var = 0; < employees.length; i++) {     if (employees[i].firstname == "anna") {         document.getelementbyid("demo").innerhtml = employees[i].lastname;         break;     } } 

to display more 1 anna - i'd use filter on array, , join:

var lastnames = employees.filter(function(employee) {     return employee.firstname == "anna"; }).map(function(employee) {     return employee.lastname; }).join(",");  document.getelementbyid("demo").innerhtml = lastnames; 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -