How to get specific data from a list of JSON - javascript

I have this JSON
{
"doctors": [
{
"id": 8,
"schedules": [
{
"id": 8,
"totime": "11:17",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "10:17",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "d1",
"degree": "DA(Anaesthesia)",
"email": "1#2.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "d1",
"userid": 51,
"gender": "Male",
"mobile": "1234567900"
},
{
"id": 10,
"schedules": [
{
"id": 10,
"totime": "12:35",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "11:35",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "d3",
"degree": "BDS",
"email": "d3#d3.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "d3",
"userid": 56,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 1,
"schedules": [
{
"id": 1,
"totime": "12:55",
"dayId": 1,
"location": "Somajiguda",
"fromtime": "11:55",
"hospitalId": 5,
"day": "Monday",
"hospital": "Yashoda"
}
],
"username": "doctor",
"degree": "BDS",
"email": "",
"imagePath": null,
"department": "Critical Care",
"name": "doctor",
"userid": 4,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 7,
"schedules": [
{
"id": 7,
"totime": "11:17",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "11:17",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "donald",
"degree": "DA(Anaesthesia)",
"email": "donald#doctor.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "donald",
"userid": 47,
"gender": "Male",
"mobile": "1234567989"
},
{
"id": 6,
"schedules": [
{
"id": 6,
"totime": "11:15",
"dayId": 1,
"location": "Somajiguda",
"fromtime": "11:15",
"hospitalId": 5,
"day": "Monday",
"hospital": "Yashoda"
}
],
"username": "john",
"degree": "BDS",
"email": "john#john.com",
"imagePath": null,
"department": "Anesthesiology",
"name": "john",
"userid": 46,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 5,
"schedules": [
{
"id": 5,
"totime": "13:11",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "12:11",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "sknayak",
"degree": "BDS",
"email": "sknayak#sknayak.com",
"imagePath": "",
"department": "Anesthesiology",
"name": "sknayak",
"userid": 38,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 2,
"schedules": [
{
"id": 2,
"totime": "16:26",
"dayId": 6,
"location": "Somajiguda",
"fromtime": "15:26",
"hospitalId": 5,
"day": "Saturday",
"hospital": "Yashoda"
}
],
"username": "drsukant",
"degree": "BDS",
"email": "",
"imagePath": null,
"department": "Anesthesiology",
"name": "sukant",
"userid": 9,
"gender": "Male",
"mobile": "1234567890"
}
]
}
In this JSON there is a field id which is unique.I am getting this json via an ajax like this
var test=$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType:"json",
jsonp: true,
async:false
}).responseText;
console.log(test);
As you can see in the JSON there is a field id.For example for id=8 username is d1,id=10,username is d3.I am storing the id in session.So for example if id is 8 then I want only those details(username d1,email 1#2.com.....) whose id is 8.
So how to filter the JSON to a specific value.

You can create a computed for a specific item:
self.doctors = ko.observableArray();
self.d3Doctor = ko.computed(function() {
return ko.utils.arrayFirst(self.doctors(), function(obj) {
return obj.id === 8;
});
});
Now you only have to worry about populating the doctors observableArray:
$.getJSON(projectUrl+"getDoctors", function(response) {
ko.utils.arrayPushAll(yourViewModel.doctors, response.doctors);
});
This allows for the following:
<div data-bind="if: d3Doctor()">
<h3>Doctor with ID 8</h3>
<p>Name: <span data-bind="text: d3Doctor().name"></span></p>
<p>E-mail: <span data-bind="text: d3Doctor().email"></span></p>
<p>Address: <span data-bind="text: d3Doctor().address"></span></p>
...
</div>

You can use each to find it, try this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType: "json",
jsonp: true,
async: false
}).done(function(data) {
$.each(data.doctors, function(i, v) {
if (v.id == '8') {
console.log('found', v.username, v.email);
return false;
}
});
});
});

May be this?:
function findById(data, id){
for(var i=0;i<data.length;i++){
if(data[i].id === id) return { username:data[i].username, email:data[i].email};
}
// Or, you can use $.grep like this:
// var foundDoctors = $.grep(data,function(e){return e.id === id;})
// return foundDoctors.length > 0 && foundDoctors[0] || null;
// Or, you can use filter() method from Array (IE 9+)
}
findById(jsondata["doctors"], 8);

Yes. I can answer this.
In my way, I personally prefer to turn all the data into array and itenerate it or manipulate it.
As mention in this question, we already push the data into this format:
doctors.push({id:currPat.id,name:currPat.username});
So, now I can use the array filter function for doctors array:
var result = doctors.filter(function(currentObject) {
return currentObject.id === 8;
});
console.log(result); // {id: 8, name:d1}
Or you can also use the .map() in JQuery, and just make the function to check the data.id and return the pair you want.
And if you would fight for a nano seconds performance. I would guess my method is better than .map()

Related

Sort Data based on mla names

Hi I have this below Json Data
How i can show only mla name list in the UI and based on which mla has got more votes?
How i can achieve this one? help me with this
Thank you
[
{
"id": 6,
"mla": [
{
"id": 16,
"votes": 1,
"name": "Shrimant",
"image": "http://localhost:8000/media/uploads/images/assignment_image.png",
"category": "MLA",
"zipcode": 591320,
"age": 49,
"email": "shrimant#gmail.com",
"contact_number": 58966663144,
"party": 1,
"state": 4,
"district": 5,
"constituency": 6
},
{
"id": 19,
"votes": 3,
"name": "Shetal Patil",
"image": "http://localhost:8000/media/uploads/images/7_oHBWq6E.png",
"category": "MLA",
"zipcode": 591320,
"age": 35,
"email": "shetal#gmail.com",
"contact_number": 8523697410,
"party": 2,
"state": 4,
"district": 5,
"constituency": 6
},
{
"id": 20,
"votes": 2,
"name": "Raju Kage",
"image": "http://localhost:8000/media/uploads/images/new1_MIaR3xQ.png",
"category": "MLA",
"zipcode": 591320,
"age": 50,
"email": "raju#gmail.com",
"contact_number": 8963257410,
"party": 3,
"state": 4,
"district": 5,
"constituency": 6
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Kagwad"
},
{
"id": 7,
"mla": [
{
"id": 9,
"votes": 1,
"name": "Chandra Metal Mart",
"image": "http://localhost:8000/media/uploads/images/2.png",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "raju#gmail.com",
"contact_number": 4294264242,
"party": 1,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 10,
"votes": 3,
"name": "Vaibhav",
"image": "http://localhost:8000/media/uploads/images/4.png",
"category": "MLA",
"zipcode": 638103,
"age": 34,
"email": "duryodhan#gmail.com",
"contact_number": 4294264242,
"party": 2,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 12,
"votes": 2,
"name": "MLA 1",
"image": "http://localhost:8000/media/uploads/images/7.png",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "vaibhav#df.com",
"contact_number": 4294264242,
"party": 3,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 21,
"votes": 1,
"name": "Gajanan",
"image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM.jpeg",
"category": "MLA",
"zipcode": 638103,
"age": 45,
"email": "can1#gmail.com",
"contact_number": 4294264242,
"party": 5,
"state": 4,
"district": 5,
"constituency": 7
},
{
"id": 22,
"votes": 1,
"name": "Pranav Singh",
"image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM_W9hWtbF.jpeg",
"category": "MLA",
"zipcode": 638103,
"age": 25,
"email": "raju#kage.com",
"contact_number": 4294264242,
"party": 6,
"state": 4,
"district": 5,
"constituency": 7
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Chikodi"
},
{
"id": 8,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Navlgund"
},
{
"id": 9,
"mla": [
{
"id": 11,
"votes": 3,
"name": "Shetter",
"image": "http://localhost:8000/media/uploads/images/images_2.jpg",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "raju#gmail.com",
"contact_number": 4294264242,
"party": 1,
"state": 4,
"district": 6,
"constituency": 9
},
{
"id": 14,
"votes": 0,
"name": "Ramulu",
"image": "http://localhost:8000/media/uploads/images/2_mK5SuIZ.png",
"category": "MLA",
"zipcode": 638103,
"age": 27,
"email": "raju#kage.com",
"contact_number": 4294264242,
"party": 3,
"state": 4,
"district": 6,
"constituency": 9
},
{
"id": 15,
"votes": 1,
"name": "Ravi",
"image": "http://localhost:8000/media/uploads/images/new1.png",
"category": "MLA",
"zipcode": 638103,
"age": 27,
"email": "raju#kage.com",
"contact_number": 4294264242,
"party": 2,
"state": 4,
"district": 6,
"constituency": 9
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Kalghatgi"
},
{
"id": 10,
"mla": [],
"state": "Tamil Nadu",
"state_id": 5,
"district": "Tripur",
"district_id": 7,
"constituency": "tripur1"
},
{
"id": 11,
"mla": [],
"state": "Tamil Nadu",
"state_id": 5,
"district": "Tripur",
"district_id": 7,
"constituency": "tripur2"
},
{
"id": 12,
"mla": [],
"state": "Maharastra",
"state_id": 6,
"district": "Karad",
"district_id": 10,
"constituency": "karad1"
},
{
"id": 13,
"mla": [
{
"id": 17,
"votes": 2,
"name": "Sashikala Jolle",
"image": "http://localhost:8000/media/uploads/images/2_Plb3dTO.png",
"category": "MLA",
"zipcode": 638103,
"age": 50,
"email": "jolle#gmail.com",
"contact_number": 4294264242,
"party": 1,
"state": 4,
"district": 5,
"constituency": 13
},
{
"id": 18,
"votes": 0,
"name": "MLA 23",
"image": "http://localhost:8000/media/uploads/images/3.png",
"category": "MLA",
"zipcode": 638103,
"age": 23,
"email": "raju#gmail.com",
"contact_number": 4294264242,
"party": 2,
"state": 4,
"district": 5,
"constituency": 13
}
],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Nippani"
},
{
"id": 14,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Gokak"
},
{
"id": 15,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Bailhongal"
},
{
"id": 16,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Kudachi"
},
{
"id": 17,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Belgavi",
"district_id": 5,
"constituency": "Raybag"
},
{
"id": 18,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Kundgol"
},
{
"id": 19,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Dharwad",
"district_id": 6,
"constituency": "Navalgund"
},
{
"id": 20,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Bangalore",
"district_id": 11,
"constituency": "Bangalore-east"
},
{
"id": 21,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Bangalore",
"district_id": 11,
"constituency": "Bangalore-west"
},
{
"id": 22,
"mla": [],
"state": "Karanataka",
"state_id": 4,
"district": "Bangalore",
"district_id": 11,
"constituency": "Bangalore-south"
}
]
Use the following code
var mlas = []; // WHICH STORES LIST OF MLAS WITH HIGHEST VOTED
// PICKING MLA DATA FROM THE JSON
jsonData.forEach(e => {
mlas = mlas.concat(e.mla);
});
//SORTING ON VOTES
var sorted = mlas.sort((a,b) => b.votes - a.votes);
You could map, filter, flatten and sort the data to get the result set you need and then use JavaScript to create the list. Working solution below.
<html>
<body>
<div>
<ul id="mla-list">
</ul>
<div>
<script>
const data = [{ "id": 6, "mla": [{ "id": 16, "votes": 1, "name": "Shrimant", "image": "http://localhost:8000/media/uploads/images/assignment_image.png", "category": "MLA", "zipcode": 591320, "age": 49, "email": "shrimant#gmail.com", "contact_number": 58966663144, "party": 1, "state": 4, "district": 5, "constituency": 6 }, { "id": 19, "votes": 3, "name": "Shetal Patil", "image": "http://localhost:8000/media/uploads/images/7_oHBWq6E.png", "category": "MLA", "zipcode": 591320, "age": 35, "email": "shetal#gmail.com", "contact_number": 8523697410, "party": 2, "state": 4, "district": 5, "constituency": 6 }, { "id": 20, "votes": 2, "name": "Raju Kage", "image": "http://localhost:8000/media/uploads/images/new1_MIaR3xQ.png", "category": "MLA", "zipcode": 591320, "age": 50, "email": "raju#gmail.com", "contact_number": 8963257410, "party": 3, "state": 4, "district": 5, "constituency": 6 }], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Kagwad" }, { "id": 7, "mla": [{ "id": 9, "votes": 1, "name": "Chandra Metal Mart", "image": "http://localhost:8000/media/uploads/images/2.png", "category": "MLA", "zipcode": 638103, "age": 23, "email": "raju#gmail.com", "contact_number": 4294264242, "party": 1, "state": 4, "district": 5, "constituency": 7 }, { "id": 10, "votes": 3, "name": "Vaibhav", "image": "http://localhost:8000/media/uploads/images/4.png", "category": "MLA", "zipcode": 638103, "age": 34, "email": "duryodhan#gmail.com", "contact_number": 4294264242, "party": 2, "state": 4, "district": 5, "constituency": 7 }, { "id": 12, "votes": 2, "name": "MLA 1", "image": "http://localhost:8000/media/uploads/images/7.png", "category": "MLA", "zipcode": 638103, "age": 23, "email": "vaibhav#df.com", "contact_number": 4294264242, "party": 3, "state": 4, "district": 5, "constituency": 7 }, { "id": 21, "votes": 1, "name": "Gajanan", "image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM.jpeg", "category": "MLA", "zipcode": 638103, "age": 45, "email": "can1#gmail.com", "contact_number": 4294264242, "party": 5, "state": 4, "district": 5, "constituency": 7 }, { "id": 22, "votes": 1, "name": "Pranav Singh", "image": "http://localhost:8000/media/uploads/images/WhatsApp_Image_2020-11-04_at_7.56.56_PM_W9hWtbF.jpeg", "category": "MLA", "zipcode": 638103, "age": 25, "email": "raju#kage.com", "contact_number": 4294264242, "party": 6, "state": 4, "district": 5, "constituency": 7 }], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Chikodi" }, { "id": 8, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Navlgund" }, { "id": 9, "mla": [{ "id": 11, "votes": 3, "name": "Shetter", "image": "http://localhost:8000/media/uploads/images/images_2.jpg", "category": "MLA", "zipcode": 638103, "age": 23, "email": "raju#gmail.com", "contact_number": 4294264242, "party": 1, "state": 4, "district": 6, "constituency": 9 }, { "id": 14, "votes": 0, "name": "Ramulu", "image": "http://localhost:8000/media/uploads/images/2_mK5SuIZ.png", "category": "MLA", "zipcode": 638103, "age": 27, "email": "raju#kage.com", "contact_number": 4294264242, "party": 3, "state": 4, "district": 6, "constituency": 9 }, { "id": 15, "votes": 1, "name": "Ravi", "image": "http://localhost:8000/media/uploads/images/new1.png", "category": "MLA", "zipcode": 638103, "age": 27, "email": "raju#kage.com", "contact_number": 4294264242, "party": 2, "state": 4, "district": 6, "constituency": 9 }], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Kalghatgi" }, { "id": 10, "mla": [], "state": "Tamil Nadu", "state_id": 5, "district": "Tripur", "district_id": 7, "constituency": "tripur1" }, { "id": 11, "mla": [], "state": "Tamil Nadu", "state_id": 5, "district": "Tripur", "district_id": 7, "constituency": "tripur2" }, { "id": 12, "mla": [], "state": "Maharastra", "state_id": 6, "district": "Karad", "district_id": 10, "constituency": "karad1" }, { "id": 13, "mla": [{ "id": 17, "votes": 2, "name": "Sashikala Jolle", "image": "http://localhost:8000/media/uploads/images/2_Plb3dTO.png", "category": "MLA", "zipcode": 638103, "age": 50, "email": "jolle#gmail.com", "contact_number": 4294264242, "party": 1, "state": 4, "district": 5, "constituency": 13 }, { "id": 18, "votes": 0, "name": "MLA 23", "image": "http://localhost:8000/media/uploads/images/3.png", "category": "MLA", "zipcode": 638103, "age": 23, "email": "raju#gmail.com", "contact_number": 4294264242, "party": 2, "state": 4, "district": 5, "constituency": 13 }], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Nippani" }, { "id": 14, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Gokak" }, { "id": 15, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Bailhongal" }, { "id": 16, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Kudachi" }, { "id": 17, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Belgavi", "district_id": 5, "constituency": "Raybag" }, { "id": 18, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Kundgol" }, { "id": 19, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Dharwad", "district_id": 6, "constituency": "Navalgund" }, { "id": 20, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Bangalore", "district_id": 11, "constituency": "Bangalore-east" }, { "id": 21, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Bangalore", "district_id": 11, "constituency": "Bangalore-west" }, { "id": 22, "mla": [], "state": "Karanataka", "state_id": 4, "district": "Bangalore", "district_id": 11, "constituency": "Bangalore-south" }];
const mlaNames = data.map(d => d.mla)
.filter(mla => mla.length > 0)
.flat()
.sort((mla1, mla2) => mla2.votes - mla1.votes)
.map(mla => mla.name);
const list = document.getElementById("mla-list");
mlaNames.forEach(mlaName => {
const li = document.createElement("li");
li.innerText = mlaName;
list.appendChild(li);
});
</script>
</body>

For to mount json

I have in variable bookUnitIdInformacoes this array of objects:
[
{
"id": 5,
"book_id": 33,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:21",
"updated_at": "2019-12-30 14:54:12",
"miniature": null
},
{
"id": 6,
"book_id": 33,
"unit": 1,
"sequence": 2,
"description": "UNIT_01_VOCABULARY",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:39",
"updated_at": "2019-12-27 08:11:39",
"miniature": null
},
{
"id": 7,
"book_id": 33,
"unit": 2,
"sequence": 1,
"description": "UNIT_02_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:46",
"updated_at": "2019-12-27 08:11:46",
"miniature": null
},
{
"id": 8,
"book_id": 39,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:07:09",
"updated_at": "2019-12-30 15:03:50",
"miniature": null
}
]
I have in the variable idioma this array of objects:
[
{
"id": 13,
"code": "ING-NOT-2019",
"description": "Inglês Noturno 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Noturno",
"language": "Inglês",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 10:04:47",
"updated_at": "2020-01-05 16:08:00",
"language_substring": "US"
},
{
"id": 14,
"code": "ESP-MAN-2019",
"description": "Espanhol manhã 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Manhã",
"language": "Espanhol",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:06:44",
"updated_at": "2019-12-30 11:06:44",
"language_substring": null
}
]
I need to create a for() that while the column book_id is equal the index+1, insert in idioma[i].quiz the value of the bookUnitIdInformacoes[i] and when the book_id of the bookUnitIdInformacoes array is different, put in the next position of idioma[i]quiz, so i need this json:
[
{
"id": 13,
"code": "ING-NOT-2019",
"description": "Inglês Noturno 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Noturno",
"language": "Inglês",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 10:04:47",
"updated_at": "2020-01-05 16:08:00",
"language_substring": "US",
"quiz": [
{
"id": 5,
"book_id": 33,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:21",
"updated_at": "2019-12-30 14:54:12",
"miniature": null
},
{
"id": 6,
"book_id": 33,
"unit": 1,
"sequence": 2,
"description": "UNIT_01_VOCABULARY",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:39",
"updated_at": "2019-12-27 08:11:39",
"miniature": null
},
{
"id": 7,
"book_id": 33,
"unit": 2,
"sequence": 1,
"description": "UNIT_02_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-27 08:11:46",
"updated_at": "2019-12-27 08:11:46",
"miniature": null
}
]
},
{
"id": 14,
"code": "ESP-MAN-2019",
"description": "Espanhol manhã 2019",
"start_date": "2019-12-30T03:00:00.000Z",
"end_date": "2019-12-31T03:00:00.000Z",
"period": "Manhã",
"language": "Espanhol",
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:06:44",
"updated_at": "2019-12-30 11:06:44",
"language_substring": null,
"quiz": [
{
"id": 8,
"book_id": 39,
"unit": 1,
"sequence": 1,
"description": "UNIT_01_GRAMMAR",
"qt_question": 5,
"status": false,
"user_id": 1,
"created_at": "2019-12-30 11:07:09",
"updated_at": "2019-12-30 15:03:50",
"miniature": null
}
]
}
]
I try something like:
for(let i=0;i<quizAbertos.length;i++){
if(i+1 === quizAbertos.length){
break;
}else{
if(bookUnitIdInformacoes[i].book_id === bookUnitIdInformacoes[i+1].book_id){
idioma[i].quiz = bookUnitIdInformacoes[i]
}
}
But i'm getting wrong json..
#Edit:
Actually i'm trying something like:
let book_id
let i_book_id = 0
let i_mudou_book_id = 0;
for(let i=0;i<bookUnitIdInformacoes.length;i++){
if(bookUnitIdInformacoes[i+1] === undefined){
book_id = bookUnitIdInformacoes[bookUnitIdInformacoes.length-1].book_id
}else{
if(bookUnitIdInformacoes[i].book_id === bookUnitIdInformacoes[i+1].book_id){
i_mudou_book_id++
}
}
}
idioma[0].quiz = bookUnitIdInformacoes.splice(0,i_mudou_book_id+1)
idioma[1].quiz = bookUnitIdInformacoes
but this way if i have more than 2 length i will be have problems and if i have only one length i will be too have problems.
First, you can group the bookUnitIdInfomacoes by book_id. This can be done by reducing the array into an object of key => value pairs as book_id => array of books:
{
"33": [
{
"id": 5,
"book_id": 33,
...
},
{
"id": 6,
"book_id": 33,
...
},
{
"id": 7,
"book_id": 33,
...
}
],
"39": [
{
"id": 8,
"book_id": 39,
...
}
]
}
Then, using Object.values will allow us to retrieve only the values of this groupedObj object. This will give us:
[
[
{
"id": 5,
"book_id": 33,
...
},
{
"id": 6,
"book_id": 33,
...
},
{
"id": 7,
"book_id": 33,
...
}
],
[
{
"id": 8,
"book_id": 39,
...
}
]
]
Lastly, we will have to map idiomas and add the corresponding book group into a new property called quizz. For a given idioma, we know its position in idiomas thanks to the second argument of map: i. We can simply do grouped[i] to get the corresponding group of books.
const groupedObj = bookUnitIdInformacoes.reduce((grouped, info) => {
grouped[info.book_id] = grouped[info.book_id] || [];
grouped[info.book_id].push(info);
return grouped;
}, {});
const grouped = Object.values(groupedObj);
const result = idiomas.map((idioma, i) => ({
...idioma,
quizz: grouped[i]
}));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script>const bookUnitIdInformacoes=[{id:5,book_id:33,unit:1,sequence:1,description:"UNIT_01_GRAMMAR",qt_question:5,status:!1,user_id:1,created_at:"2019-12-27 08:11:21",updated_at:"2019-12-30 14:54:12",miniature:null},{id:6,book_id:33,unit:1,sequence:2,description:"UNIT_01_VOCABULARY",qt_question:5,status:!1,user_id:1,created_at:"2019-12-27 08:11:39",updated_at:"2019-12-27 08:11:39",miniature:null},{id:7,book_id:33,unit:2,sequence:1,description:"UNIT_02_GRAMMAR",qt_question:5,status:!1,user_id:1,created_at:"2019-12-27 08:11:46",updated_at:"2019-12-27 08:11:46",miniature:null},{id:8,book_id:39,unit:1,sequence:1,description:"UNIT_01_GRAMMAR",qt_question:5,status:!1,user_id:1,created_at:"2019-12-30 11:07:09",updated_at:"2019-12-30 15:03:50",miniature:null}],idiomas=[{id:13,code:"ING-NOT-2019",description:"Inglês Noturno 2019",start_date:"2019-12-30T03:00:00.000Z",end_date:"2019-12-31T03:00:00.000Z",period:"Noturno",language:"Inglês",status:!1,user_id:1,created_at:"2019-12-30 10:04:47",updated_at:"2020-01-05 16:08:00",language_substring:"US"},{id:14,code:"ESP-MAN-2019",description:"Espanhol manhã 2019",start_date:"2019-12-30T03:00:00.000Z",end_date:"2019-12-31T03:00:00.000Z",period:"Manhã",language:"Espanhol",status:!1,user_id:1,created_at:"2019-12-30 11:06:44",updated_at:"2019-12-30 11:06:44",language_substring:null}];</script>

JavaScript - Search object property by key and add its value to array

Let's say I have an object like this:
var object = {
"Defender": {
"player-1868": {
"birthdate": "1 July 1996",
"club_country": "IQ",
"club_id": 171,
"club_name": "Erbil",
"forename": "Burhan Jumaah",
"id": 1868,
"league_id": 12,
"league_name": "Iraqi Premier League",
"name": "Burhan Jumaah",
"nationality": "iq",
"nationality_full": "Iraq",
"position": "Defender",
"surname": "Razzaq",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
}
},
"Goalkeeper": {
"player-3076": {
"birthdate": "15 December 1985",
"club_country": "QA",
"club_id": 1,
"club_name": "Lekhwiya",
"comments": [
{
"comment": "xxx",
"name": "guy tester",
"photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
"time": 1496529030321,
"user": "y884F42mLCVdld5V5cMeRpl11gJ2"
}
],
"forename": "Qasem Abdulhamed",
"id": 3076,
"league_id": 1,
"league_name": "Qatar Stars League",
"name": "Qasem Burhan",
"nationality": "qa",
"nationality_full": "Qatar",
"position": "Goalkeeper",
"surname": "Burhan",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
},
"player-3532": {
"birthdate": "2 April 1992",
"club_country": "SA",
"club_id": 18,
"club_name": "Al Ittihad",
"forename": "Fawaz",
"id": 3532,
"league_id": 2,
"league_name": "Saudi Professional League",
"name": "Fawaz Al Qarni",
"nationality": "sa",
"nationality_full": "Saudi Arabia",
"position": "Goalkeeper",
"surname": "Al Qarni",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
}
}
};
How would I, using lodash, traverse through this object and add every time the property id appears inside an object key of player-xxxxxx, add that value to an array. Essentially, getting all of the player IDs in a single array?
You can Array#reduce recursively on the object's keys to find the search string (player-), and create and extract the values:
var object = {"Defender":{"player-1868":{"birthdate":"1 July 1996","club_country":"IQ","club_id":171,"club_name":"Erbil","forename":"Burhan Jumaah","id":1868,"league_id":12,"league_name":"Iraqi Premier League","name":"Burhan Jumaah","nationality":"iq","nationality_full":"Iraq","position":"Defender","surname":"Razzaq","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]}},"Goalkeeper":{"player-3076":{"birthdate":"15 December 1985","club_country":"QA","club_id":1,"club_name":"Lekhwiya","comments":[{"comment":"xxx","name":"guy tester","photoURL":"http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg","time":1496529030321,"user":"y884F42mLCVdld5V5cMeRpl11gJ2"}],"forename":"Qasem Abdulhamed","id":3076,"league_id":1,"league_name":"Qatar Stars League","name":"Qasem Burhan","nationality":"qa","nationality_full":"Qatar","position":"Goalkeeper","surname":"Burhan","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]},"player-3532":{"birthdate":"2 April 1992","club_country":"SA","club_id":18,"club_name":"Al Ittihad","forename":"Fawaz","id":3532,"league_id":2,"league_name":"Saudi Professional League","name":"Fawaz Al Qarni","nationality":"sa","nationality_full":"Saudi Arabia","position":"Goalkeeper","surname":"Al Qarni","votes":["y884F42mLCVdld5V5cMeRpl11gJ2"]}}};
function searchProps(searchStr, object) {
return Object.keys(object).reduce(function(arr, key) { // reduce the objects keys to an array
key.indexOf(searchStr) === -1 || arr.push(key.slice(searchStr.length)); // if a key contains the search string, take whatever after it
var propValue = object[key];
if(typeof propValue === 'object' && propValue !== null) { // if the value of the property is an array, run it through search props
return arr.concat(searchProps(searchStr, propValue));
}
return arr;
}, []);
}
var result = searchProps('player-', object);
console.log(result);
With Javascript, to traverse the keys and get each id, you may use "for" like below sample code:
var obj = {
"Defender": {
"player-1868": {
"birthdate": "1 July 1996",
"club_country": "IQ",
"club_id": 171,
"club_name": "Erbil",
"forename": "Burhan Jumaah",
"id": 1868,
"league_id": 12,
"league_name": "Iraqi Premier League",
"name": "Burhan Jumaah",
"nationality": "iq",
"nationality_full": "Iraq",
"position": "Defender",
"surname": "Razzaq",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
}
},
"Goalkeeper": {
"player-3076": {
"birthdate": "15 December 1985",
"club_country": "QA",
"club_id": 1,
"club_name": "Lekhwiya",
"comments": [
{
"comment": "xxx",
"name": "guy tester",
"photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
"time": 1496529030321,
"user": "y884F42mLCVdld5V5cMeRpl11gJ2"
}
],
"forename": "Qasem Abdulhamed",
"id": 3076,
"league_id": 1,
"league_name": "Qatar Stars League",
"name": "Qasem Burhan",
"nationality": "qa",
"nationality_full": "Qatar",
"position": "Goalkeeper",
"surname": "Burhan",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
},
"player-3532": {
"birthdate": "2 April 1992",
"club_country": "SA",
"club_id": 18,
"club_name": "Al Ittihad",
"forename": "Fawaz",
"id": 3532,
"league_id": 2,
"league_name": "Saudi Professional League",
"name": "Fawaz Al Qarni",
"nationality": "sa",
"nationality_full": "Saudi Arabia",
"position": "Goalkeeper",
"surname": "Al Qarni",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
}
}
};
var arr = [];
tgtObj = obj["Defender"];
for(var key in tgtObj){
if (tgtObj.hasOwnProperty(key)){
console.log(key);
arr.push(tgtObj[key]["id"]);
}
}
tgtObj = obj["Goalkeeper"];
for(var key in tgtObj){
if (tgtObj.hasOwnProperty(key)){
console.log(key);
arr.push(tgtObj[key]["id"]);
}
}
console.log(arr);
Iterate through the object keys check to see if the string starts with "player-" and then push into an empty array the last four characters.
var object = {
"Defender": {
"player-1868": {
"birthdate": "1 July 1996",
"club_country": "IQ",
"club_id": 171,
"club_name": "Erbil",
"forename": "Burhan Jumaah",
"id": 1868,
"league_id": 12,
"league_name": "Iraqi Premier League",
"name": "Burhan Jumaah",
"nationality": "iq",
"nationality_full": "Iraq",
"position": "Defender",
"surname": "Razzaq",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
}
},
"Goalkeeper": {
"player-3076": {
"birthdate": "15 December 1985",
"club_country": "QA",
"club_id": 1,
"club_name": "Lekhwiya",
"comments": [{
"comment": "xxx",
"name": "guy tester",
"photoURL": "http://pbs.twimg.com/profile_images/855450315704979460/RGiq07D7_normal.jpg",
"time": 1496529030321,
"user": "y884F42mLCVdld5V5cMeRpl11gJ2"
}],
"forename": "Qasem Abdulhamed",
"id": 3076,
"league_id": 1,
"league_name": "Qatar Stars League",
"name": "Qasem Burhan",
"nationality": "qa",
"nationality_full": "Qatar",
"position": "Goalkeeper",
"surname": "Burhan",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
},
"player-3532": {
"birthdate": "2 April 1992",
"club_country": "SA",
"club_id": 18,
"club_name": "Al Ittihad",
"forename": "Fawaz",
"id": 3532,
"league_id": 2,
"league_name": "Saudi Professional League",
"name": "Fawaz Al Qarni",
"nationality": "sa",
"nationality_full": "Saudi Arabia",
"position": "Goalkeeper",
"surname": "Al Qarni",
"votes": [
"y884F42mLCVdld5V5cMeRpl11gJ2"
]
}
}
};
function getPlayers(object) {
let items = [];
for (let i in object) {
let key = Object.keys(object[i]);
key.forEach(i => i.startsWith('player') ? items.push(i.substring(i.length -4)) : '');
}
return items;
}
console.log(getPlayers(object));
I was able to solve it myself after some more time on it.
var obj = {
Defender: {
"player-1868": {
club_id: 171,
id: 1868,
league_id: 12,
name: "Burhan Jumaah"
}
},
Goalkeeper: {
"player-3076": {
club_id: 1,
id: 3076,
league_id: 1,
name: "Qasem Burhan"
},
"player-3532": {
club_id: 18,
id: 3532,
league_id: 2,
name: "Fawaz Al Qarni"
}
}
};
function searchForProp(lookingFor, obj, arrYielded) {
var arr = arrYielded ? arrYielded : [];
Object.keys(obj).forEach(function(key, idx) {
if (typeof(obj[key]) === 'object') {
searchForProp(lookingFor, obj[key], arr);
} else {
if (key === 'id') {
arr.push(obj[key]);
}
}
});
return arr;
}
var allIDs = searchForProp('id', obj);
console.log(allIDs);
The simplest way that I could think of using lodash:
_(object).map(_.keys).flatten().value();
This of course assumes that the player keys are always at the same level in the object hierarchy.

How to push 2 items to an array

In this fiddle line 27 shows
var doctors = [
new Doctor("Doc A","A1"),
new Doctor("Doc B","A1"),
new Doctor("Doc C","A3")
];
Here, Doc A, Doc B and Doc C are hard-coded. They are also Knockout bindings:
ko.applyBindings(
new Patient("idValue", "nameValue", "addressValue", "Female", "usernameValue",
"passwordValue", "emailValue", "mobileValue", "imgFileValue",
"imgSrcValue", "imagePathValue", "useridValue", "A3")
);
Whatever is passed a1, a2 or a3 selects the respective doc. For example, I am passing a3 in the bindings, so I get Doc C selected.
Given this JSON:
{
"doctors": [
{
"id": 8,
"schedules": [
{
"id": 8,
"totime": "11:17",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "10:17",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "d1",
"degree": "DA(Anaesthesia)",
"email": "1#2.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "d1",
"userid": 51,
"gender": "Male",
"mobile": "1234567900"
},
{
"id": 10,
"schedules": [
{
"id": 10,
"totime": "12:35",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "11:35",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "d3",
"degree": "BDS",
"email": "d3#d3.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "d3",
"userid": 56,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 1,
"schedules": [
{
"id": 1,
"totime": "12:55",
"dayId": 1,
"location": "Somajiguda",
"fromtime": "11:55",
"hospitalId": 5,
"day": "Monday",
"hospital": "Yashoda"
}
],
"username": "doctor",
"degree": "BDS",
"email": "",
"imagePath": null,
"department": "Critical Care",
"name": "doctor",
"userid": 4,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 7,
"schedules": [
{
"id": 7,
"totime": "11:17",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "11:17",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "donald",
"degree": "DA(Anaesthesia)",
"email": "donald#doctor.com",
"imagePath": "",
"department": "Bio-Chemistry",
"name": "donald",
"userid": 47,
"gender": "Male",
"mobile": "1234567989"
},
{
"id": 6,
"schedules": [
{
"id": 6,
"totime": "11:15",
"dayId": 1,
"location": "Somajiguda",
"fromtime": "11:15",
"hospitalId": 5,
"day": "Monday",
"hospital": "Yashoda"
}
],
"username": "john",
"degree": "BDS",
"email": "john#john.com",
"imagePath": null,
"department": "Anesthesiology",
"name": "john",
"userid": 46,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 5,
"schedules": [
{
"id": 5,
"totime": "13:11",
"dayId": 2,
"location": "Somajiguda",
"fromtime": "12:11",
"hospitalId": 5,
"day": "Tuesday",
"hospital": "Yashoda"
}
],
"username": "sknayak",
"degree": "BDS",
"email": "sknayak#sknayak.com",
"imagePath": "",
"department": "Anesthesiology",
"name": "sknayak",
"userid": 38,
"gender": "Male",
"mobile": "1234567890"
},
{
"id": 2,
"schedules": [
{
"id": 2,
"totime": "16:26",
"dayId": 6,
"location": "Somajiguda",
"fromtime": "15:26",
"hospitalId": 5,
"day": "Saturday",
"hospital": "Yashoda"
}
],
"username": "drsukant",
"degree": "BDS",
"email": "",
"imagePath": null,
"department": "Anesthesiology",
"name": "sukant",
"userid": 9,
"gender": "Male",
"mobile": "1234567890"
}
]
}
Obtained with a GET request:
$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType:"json",
jsonp: true,
async:false ,
success: function (data) {
$.each(data.doctors, function(index, currPat) {
console.log(currPat.username);
});
}
});
I want username and ID from the JSON in place of 'Doc A', 'a1', 'Doc B', 'a2', etc... as a replacement for var doctors = ....
In my AJAX success, I tried:
success: function (data) {
$.each(data.doctors, function(index, currPat) {
new Doctors(currPat.id,currPat.username);
});
}
May be something like this?
var doctors = [];
$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType:"json",
jsonp: true,
async:false ,
success: function (data) {
$.each(data.doctors, function(index, currPat) {
doctors.push[currPat.id,currPat.username];
});
}
});
Your end result should be like this:
doctors = [[id1,name1],[id2,name2], ...... [id10,name10]]
Or you can also use the format like this:
doctors.push({id:currPat.id,name:currPat.username});
Then your end result should be something like this:
doctors = [{id:id1,name:name1},{id:id2,name:name2},......,{id:id10,name:name10}]
*I personally prefer format 2
EDIT Use of JQuery, .map()
var doctors;
$.ajax({
type: "GET",
url: projectUrl+"getDoctors",
dataType:"json",
jsonp: true,
async:false ,
success: function (data) {
doctors = $.map(function () {
return [data.id,data.username];}).get();
}
});
A slightly more short hand than the above mention.
It looks like jQuery.map() can do what you need...
success: function (data) {
doctors = $.map(data.doctors, function(doctor) {
new Doctor(doctor.id, doctor.username);
});
}
JSFiddle
consider your Doctor function looks like:
// Doctor constructor with name and username properties
var Doctor = function(nameParam, usernameParam){
this.name = nameParam;
this.username = usernameParam;
};
then on AJAX success function populate all received doctors like:
$.each(jsonStr.doctors, function(index, currPat) {
var doc = new Doctor(currPat.name,currPat.username);
doctors.push(doc);
});
alert(JSON.stringify(doctors));
working fiddle

Parsing JsonP with Javascript

I am trying to parse JSON data like this:
var baseUrl = 'https://api.themoviedb.org/3/movie/'
var movieID = '550'
var detailUrl = '&append_to_response=releases,trailers,credits&callback=?'
var apiKey = '?api_key=Removed_For_Privacy'
The above url with the api key include returns this result:
?({
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": "10.2188172784825",
"poster_path": "/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
},
{
"name": "Fox 2000 Pictures",
"id": 711
},
{
"name": "Regency Enterprises",
"id": 508
}
],
"production_countries": [
{
"iso_3166_1": "DE",
"name": "Germany"
},
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-14",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if you've never been in a fight?",
"title": "Fight Club",
"vote_average": 7.6,
"vote_count": 2787,
"releases": {
"countries": [
{
"iso_3166_1": "US",
"certification": "R",
"release_date": "1999-10-14"
},
{
"iso_3166_1": "DE",
"certification": "18",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "GB",
"certification": "18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "FR",
"certification": "16",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "TR",
"certification": "",
"release_date": "1999-12-10"
},
{
"iso_3166_1": "BR",
"certification": "feibris",
"release_date": "1999-07-12"
},
{
"iso_3166_1": "FI",
"certification": "K-18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "BG",
"certification": "c",
"release_date": "2012-08-28"
},
{
"iso_3166_1": "IT",
"certification": "VM14",
"release_date": "1999-10-29"
}
]
},
"trailers": {
"quicktime": [],
"youtube": [
{
"name": "Trailer 1",
"size": "HD",
"source": "SUXWAEX2jlg",
"type": "Trailer"
}
]
},
"credits": {
"cast": [
{
"id": 819,
"name": "Edward Norton",
"character": "The Narrator",
"order": 0,
"cast_id": 4,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
},
{
"id": 287,
"name": "Brad Pitt",
"character": "Tyler Durden",
"order": 1,
"cast_id": 5,
"profile_path": "/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"
},
{
"id": 1283,
"name": "Helena Bonham Carter",
"character": "Marla Singer",
"order": 2,
"cast_id": 6,
"profile_path": "/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"
},
{
"id": 7470,
"name": "Meat Loaf",
"character": "Robert 'Bob' Paulson",
"order": 3,
"cast_id": 7,
"profile_path": "/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"
},
{
"id": 7499,
"name": "Jared Leto",
"character": "Angel Face",
"order": 4,
"cast_id": 30,
"profile_path": "/msugySeTCyCmlRWtyB6sMixTQYY.jpg"
},
{
"id": 7471,
"name": "Zach Grenier",
"character": "Richard Chesler",
"order": 5,
"cast_id": 31,
"profile_path": "/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"
},
{
"id": 7497,
"name": "Holt McCallany",
"character": "The Mechanic",
"order": 6,
"cast_id": 32,
"profile_path": "/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"
},
{
"id": 7498,
"name": "Eion Bailey",
"character": "Ricky",
"order": 7,
"cast_id": 33,
"profile_path": "/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"
}
],
"crew": [
{
"id": 7469,
"name": "Jim Uhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "Ross Grayson Bell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "Ceán Chaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "Art Linson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "John King",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7478,
"name": "Michael Simpson",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7479,
"name": "Jeff Cronenweth",
"department": "Camera",
"job": "Director of Photography",
"profile_path": null
},
{
"id": 7480,
"name": "James Haygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "Laray Mayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "Alex McDowell",
"department": "Art",
"job": "Production Design",
"profile_path": null
},
{
"id": 7763,
"name": "Ren Klyce",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7764,
"name": "Richard Hymns",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7467,
"name": "David Fincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "Chuck Palahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
}
})
I use this to parse it, however i have no luck
$(document).ready(function() {
$.ajax({
url: baseUrl + movieID +apiKey +detailUrl,
dataType: "jsonp",
success: getGenres,
});
});
function getGenres(data) {
var entries = data
genre = 0,
genre_list = '';
for (genre = 0; genre < entries.genres.name.length; genre++) {
genre_list.push(entries.genres.name[genre]);
}
document.getElementById('Genres').innerHTML = genre_list.join(', ');
Please Help
entries.genres is an Array. It has no .name property. You should be getting an error in your browser's developer console for accessing .length of undefined.
{
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
...
}
So you need to iterate entries.genres, then push the .name of the current genre if that's what you want.
for (genre = 0; genre < entries.genres.length; genre++) {
genre_list.push(entries.genres[genre].name);
}
On a different note, you have two implicit globals.
var entries = data
genre = 0,
genre_list = '';
By forgetting the comma after var entries = data, the next two lines will implicitly create global variables since they're not part of the var statement.
That's why I always use leading commas for variable declarations. Makes it obvious when a comma is missing.
var entries = data
, genre = 0
, genre_list = '';
test.php
<?php
echo 'getGenres({
"adult": false,
"backdrop_path": "/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 53,
"name": "Thriller"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": "10.2188172784825",
"poster_path": "/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
},
{
"name": "Fox 2000 Pictures",
"id": 711
},
{
"name": "Regency Enterprises",
"id": 508
}
],
"production_countries": [
{
"iso_3166_1": "DE",
"name": "Germany"
},
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-14",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if youve never been in a fight?",
"title": "Fight Club",
"vote_average": 7.6,
"vote_count": 2787,
"releases": {
"countries": [
{
"iso_3166_1": "US",
"certification": "R",
"release_date": "1999-10-14"
},
{
"iso_3166_1": "DE",
"certification": "18",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "GB",
"certification": "18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "FR",
"certification": "16",
"release_date": "1999-11-10"
},
{
"iso_3166_1": "TR",
"certification": "",
"release_date": "1999-12-10"
},
{
"iso_3166_1": "BR",
"certification": "feibris",
"release_date": "1999-07-12"
},
{
"iso_3166_1": "FI",
"certification": "K-18",
"release_date": "1999-11-12"
},
{
"iso_3166_1": "BG",
"certification": "c",
"release_date": "2012-08-28"
},
{
"iso_3166_1": "IT",
"certification": "VM14",
"release_date": "1999-10-29"
}
]
},
"trailers": {
"quicktime": [],
"youtube": [
{
"name": "Trailer 1",
"size": "HD",
"source": "SUXWAEX2jlg",
"type": "Trailer"
}
]
},
"credits": {
"cast": [
{
"id": 819,
"name": "Edward Norton",
"character": "The Narrator",
"order": 0,
"cast_id": 4,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
},
{
"id": 287,
"name": "Brad Pitt",
"character": "Tyler Durden",
"order": 1,
"cast_id": 5,
"profile_path": "/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"
},
{
"id": 1283,
"name": "Helena Bonham Carter",
"character": "Marla Singer",
"order": 2,
"cast_id": 6,
"profile_path": "/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"
},
{
"id": 7470,
"name": "Meat Loaf",
"character": "Robert Bob Paulson",
"order": 3,
"cast_id": 7,
"profile_path": "/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"
},
{
"id": 7499,
"name": "Jared Leto",
"character": "Angel Face",
"order": 4,
"cast_id": 30,
"profile_path": "/msugySeTCyCmlRWtyB6sMixTQYY.jpg"
},
{
"id": 7471,
"name": "Zach Grenier",
"character": "Richard Chesler",
"order": 5,
"cast_id": 31,
"profile_path": "/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"
},
{
"id": 7497,
"name": "Holt McCallany",
"character": "The Mechanic",
"order": 6,
"cast_id": 32,
"profile_path": "/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"
},
{
"id": 7498,
"name": "Eion Bailey",
"character": "Ricky",
"order": 7,
"cast_id": 33,
"profile_path": "/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"
}
],
"crew": [
{
"id": 7469,
"name": "Jim Uhls",
"department": "Writing",
"job": "Author",
"profile_path": null
},
{
"id": 7474,
"name": "Ross Grayson Bell",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 7475,
"name": "Ceán Chaffin",
"department": "Production",
"job": "Producer",
"profile_path": null
},
{
"id": 1254,
"name": "Art Linson",
"department": "Production",
"job": "Producer",
"profile_path": "/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"
},
{
"id": 7477,
"name": "John King",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7478,
"name": "Michael Simpson",
"department": "Sound",
"job": "Original Music Composer",
"profile_path": null
},
{
"id": 7479,
"name": "Jeff Cronenweth",
"department": "Camera",
"job": "Director of Photography",
"profile_path": null
},
{
"id": 7480,
"name": "James Haygood",
"department": "Editing",
"job": "Editor",
"profile_path": null
},
{
"id": 7481,
"name": "Laray Mayfield",
"department": "Production",
"job": "Casting",
"profile_path": null
},
{
"id": 1303,
"name": "Alex McDowell",
"department": "Art",
"job": "Production Design",
"profile_path": null
},
{
"id": 7763,
"name": "Ren Klyce",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7764,
"name": "Richard Hymns",
"department": "Sound",
"job": "Sound Editor",
"profile_path": null
},
{
"id": 7467,
"name": "David Fincher",
"department": "Directing",
"job": "Director",
"profile_path": "/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"
},
{
"id": 7468,
"name": "Chuck Palahniuk",
"department": "Writing",
"job": "Novel",
"profile_path": "/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"
}
]
}
})';
exit;
?>
javascript code:
<script language="javascript">
jq(document).ready(function() {
jq.ajax({
url: 'test.php',
dataType: "jsonp",
}); });
function getGenres(data){
alert(data.genres.length);
}
</script>
Your json response contains single quotes (') example 'bob' and you've which are not standard, so replace then by \' and then parse your json response.
For reference check jQuery single quote in JSON response
Remove ?( and ) from the starting and end of json response and also remove ' from them and check
var obj = jQuery.parseJSON( '{"adult":false,"backdrop_path":"/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg","belongs_to_collection":null,"budget":63000000,"genres":[{"id":28,"name":"Action"},{"id":18,"name":"Drama"},{"id":53,"name":"Thriller"}],"homepage":"","id":550,"imdb_id":"tt0137523","original_title":"Fight Club","overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground fight clubs forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.","popularity":"10.2188172784825","poster_path":"/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg","production_companies":[{"name":"20th Century Fox","id":25},{"name":"Fox 2000 Pictures","id":711},{"name":"Regency Enterprises","id":508}],"production_countries":[{"iso_3166_1":"DE","name":"Germany"},{"iso_3166_1":"US","name":"United States of America"}],"release_date":"1999-10-14","revenue":100853753,"runtime":139,"spoken_languages":[{"iso_639_1":"en","name":"English"}],"status":"Released","tagline":"How much can you know about yourself if youve never been in a fight?","title":"Fight Club","vote_average":7.6,"vote_count":2787,"releases":{"countries":[{"iso_3166_1":"US","certification":"R","release_date":"1999-10-14"},{"iso_3166_1":"DE","certification":"18","release_date":"1999-11-10"},{"iso_3166_1":"GB","certification":"18","release_date":"1999-11-12"},{"iso_3166_1":"FR","certification":"16","release_date":"1999-11-10"},{"iso_3166_1":"TR","certification":"","release_date":"1999-12-10"},{"iso_3166_1":"BR","certification":"feibris","release_date":"1999-07-12"},{"iso_3166_1":"FI","certification":"K-18","release_date":"1999-11-12"},{"iso_3166_1":"BG","certification":"c","release_date":"2012-08-28"},{"iso_3166_1":"IT","certification":"VM14","release_date":"1999-10-29"}]},"trailers":{"quicktime":[],"youtube":[{"name":"Trailer 1","size":"HD","source":"SUXWAEX2jlg","type":"Trailer"}]},"credits":{"cast":[{"id":819,"name":"Edward Norton","character":"The Narrator","order":0,"cast_id":4,"profile_path":"/iUiePUAQKN4GY6jorH9m23cbVli.jpg"},{"id":287,"name":"Brad Pitt","character":"Tyler Durden","order":1,"cast_id":5,"profile_path":"/kc3M04QQAuZ9woUvH3Ju5T7ZqG5.jpg"},{"id":1283,"name":"Helena Bonham Carter","character":"Marla Singer","order":2,"cast_id":6,"profile_path":"/58oJPFG1wefMC0Vj7sFzHPrm67J.jpg"},{"id":7470,"name":"Meat Loaf","character":"Robert Bob Paulson","order":3,"cast_id":7,"profile_path":"/pwNyXgegO1nlZ8uWT847JM8EjGj.jpg"},{"id":7499,"name":"Jared Leto","character":"Angel Face","order":4,"cast_id":30,"profile_path":"/msugySeTCyCmlRWtyB6sMixTQYY.jpg"},{"id":7471,"name":"Zach Grenier","character":"Richard Chesler","order":5,"cast_id":31,"profile_path":"/jghYiKdNkVehKpiVyE97AWrU9KQ.jpg"},{"id":7497,"name":"Holt McCallany","character":"The Mechanic","order":6,"cast_id":32,"profile_path":"/hQBfcw9KVszdenlTZTR8AIrSpex.jpg"},{"id":7498,"name":"Eion Bailey","character":"Ricky","order":7,"cast_id":33,"profile_path":"/4MnRgrwuiJvHsfoiJrIUL4TkfoC.jpg"}],"crew":[{"id":7469,"name":"Jim Uhls","department":"Writing","job":"Author","profile_path":null},{"id":7474,"name":"Ross Grayson Bell","department":"Production","job":"Producer","profile_path":null},{"id":7475,"name":"Ceán Chaffin","department":"Production","job":"Producer","profile_path":null},{"id":1254,"name":"Art Linson","department":"Production","job":"Producer","profile_path":"/dEtVivCXxQBtIzmJcUNupT1AB4H.jpg"},{"id":7477,"name":"John King","department":"Sound","job":"Original Music Composer","profile_path":null},{"id":7478,"name":"Michael Simpson","department":"Sound","job":"Original Music Composer","profile_path":null},{"id":7479,"name":"Jeff Cronenweth","department":"Camera","job":"Director of Photography","profile_path":null},{"id":7480,"name":"James Haygood","department":"Editing","job":"Editor","profile_path":null},{"id":7481,"name":"Laray Mayfield","department":"Production","job":"Casting","profile_path":null},{"id":1303,"name":"Alex McDowell","department":"Art","job":"Production Design","profile_path":null},{"id":7763,"name":"Ren Klyce","department":"Sound","job":"Sound Editor","profile_path":null},{"id":7764,"name":"Richard Hymns","department":"Sound","job":"Sound Editor","profile_path":null},{"id":7467,"name":"David Fincher","department":"Directing","job":"Director","profile_path":"/dcBHejOsKvzVZVozWJAPzYthb8X.jpg"},{"id":7468,"name":"Chuck Palahniuk","department":"Writing","job":"Novel","profile_path":"/8nOJDJ6SqwV2h7PjdLBDTvIxXvx.jpg"}]}}' );
alert( obj.genres.length );
alert messages showing 3, so your json response is not valid

Categories