How to push 2 items to an array - javascript

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

Related

Convert an object to 3d array

I am new to node.js and javascript. I am trying to build a rest API.
For a specific purpose, I need to convert an object to 3d array.
I tried running for, foreach loop but it is not providing what I am trying to achieve.
My object looks like this.
"data": [
{
"id": 15184,
"badge_id": "330886",
"name": "Rukmani J. Solanki",
"gender": "Female",
"type": "PF",
"department": "Sales",
"checkin": "2021-09-24T08:52:44.000Z",
"checkout": "2021-09-24T08:57:45.000Z",
"hours": "00:05"
},
{
"id": 15185,
"badge_id": "440886",
"name": "Jairam J. Solanki",
"gender": "Male",
"type": "PM",
"department": "Sales",
"checkin": "2021-09-24T09:28:32.000Z",
"checkout": null,
"hours": null
}
]
And I want something like this
{
"onfield": [
{
"key": "Sales",
"data": {
"PM": [
{
"name": "Gokuldas S. Sundrani",
"badge_id": "441101",
"gender": "Male",
"checkIn": "2021-09-24 06:04:18",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "551249",
"gender": "Male",
"checkIn": "2021-09-24 06:47:31",
"checkOut": "2021-09-24 08:32:00",
"hours": "1.7 Hours"
},
{
"name": "Praveen N. Jethwani",
"badge_id": "771328",
"gender": "Male",
"checkIn": "2021-09-24 07:14:11",
"checkOut": "2021-09-24 08:29:34",
"hours": "1.3 Hours"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "88249",
"gender": "Male",
"checkIn": "2021-09-24 08:32:00",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Arjundas D. Chhabra",
"badge_id": "661248",
"gender": "Male",
"checkIn": "2021-09-24 10:19:22",
"checkOut": "2021-09-24 18:38:32",
"hours": "8.3 Hours"
},
{
"name": "Parmanand C. Lalwani",
"badge_id": "8651418",
"gender": "Male",
"checkIn": "2021-09-24 14:51:08",
"checkOut": "2021-09-24 17:39:27",
"hours": "2.8 Hours"
},
{
"name": "Dhanalal G. Chouhan",
"badge_id": "5501392",
"gender": "Male",
"checkIn": "2021-09-24 14:58:46",
"checkOut": "2021-09-24 18:20:50",
"hours": "3.4 Hours"
}
],
"PF": [
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "501993",
"gender": "Female",
"checkIn": "2021-09-24 06:47:48",
"checkOut": "2021-09-24 08:32:12",
"hours": "1.7 Hours"
},
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "801993",
"gender": "Female",
"checkIn": "2021-09-24 08:32:12",
"checkOut": null,
"hours": "NoCheckOut"
}
],
"OM": [
{
"name": "Yadvendra Bhati",
"badge_id": "2255454",
"gender": "male",
"checkIn": "2021-09-24 13:38:37",
"checkOut": "2021-09-24 17:24:11",
"hours": "3.8 Hours"
}
],
"OF": [
{
"name": "Yashoda Bhati",
"badge_id": "223F0029",
"gender": "Female",
"checkIn": "2021-09-24 13:38:44",
"checkOut": "2021-09-24 17:24:25",
"hours": "3.8 Hours"
}
]
}
}
]
}
How can this be done?
I will be really grateful to you for your help.
I have googled and searched StackOverflow but did not find anything which deals with this kind of problem.
Thank You
Although I totally agree with Juan Mendes, here is a tip in order for you to be able to accomplish this. You may get an intermediate form for your data as this one:
{
"onfield": [
{
"key": "dept1",
"data": {
"PM": [
{
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male"
}
]
}
},
{
"key": "dept2",
"data": {
"PF": [
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female"
}
]
}
},
{
"key": "dept1",
"data": {
"PM": [
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}
]
}
}
]
}
Perhaps transforming your source data to this one is easier. And getting to your target from here will be just a matter of merging arrays of the same type.
Do not hesitate to ask if this keeps being difficult. But as said, please try to solve this yourself, that's the way you are going to learn.
let data = [{ "id": 123, "badge_id": "1231", "name": "name1", "gender": "Male", "type": "PM", "dept": "dept1" }, { "id": 124, "badge_id": "1232", "name": "name2", "gender": "Female", "type": "PF", "dept": "dept2" }, { "id": 125, "badge_id": "1233", "name": "name3", "gender": "Male", "type": "PM", "dept": "dept1" }];
let Report = []
data.forEach((item) => {
let obj = Report.find(v => v.dept == item.dept);
if (!obj) Report.push(obj = {
dept: item.dept,
type: {}
});
obj.type[item.type] ??= [];
obj.type[item.type].push({
id: item.id,
badge_id: item.badge_id,
name: item.name,
gender: item.gender,
});
})
console.log(Report)
Here's Something i think is more feasible than your result .. Checkout
let myObject = {
"data": [ {
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male",
"type": "PM",
"dept": "dept1"
},
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female",
"type": "PF",
"dept": "dept2"
},
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}]
}
function generateReport(object) {
let obj = {
"Report": []
};
let types = [];
object.data.forEach(arr =>{
if(!types.includes(arr.type)){
types.push(arr.type);
}
});
types.forEach(type =>{
obj.Report.push({
type : type,
users : object.data.filter(arr=>{ let a = arr.type == type;
if(a){
delete arr.type;
}
return a;
})
});
});
return obj;
}
myObject = generateReport(myObject);
console.log(myObject)
You oculd take the wanted grouping keys in an array and destructure the object to remove this keys from the object.
Every key takes it own nested object structure.
const
data = [{ id: 123, badge_id: "1231", name: "name1", gender: "Male", type: "PM", dept: "dept1" }, { id: 124, badge_id: "1232", name: "name2", gender: "Female", type: "PF", dept: "dept2" }, { id: 125, badge_id: "1233", name: "name3", gender: "Male", type: "PM", dept: "dept1" }],
keys = ['dept', 'type'],
result = data
.reduce((r, o) => {
keys
.reduce(function (t, k) {
let key;
({ [k]: key, ...o } = o);
if (!t[key]) t._.push({ [k]: key, data: (t[key] = { _: [] })._ });
return t[key];
}, r)
._
.push(o);
return r;
}, { _: [] })
._;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Json data to javaScript Treeview

hello there is a json data as below.
var arr = [{
"ID": 1,
"parentID": 0,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
}, {
"ID": 2,
"parentID": 0,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet"
}, {
"ID": 3,
"parentID": 0,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria"
}, {
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes"
}, {
"ID": 5,
"parentID": 0,
"Phone": "(755) 968-6539",
"City": "Gönen",
"Name": "Madeson"
}, {
"ID": 6,
"parentID": 5,
"Phone": "(644) 892-5485",
"City": "Timkur",
"Name": "Rae"
}, {
"ID": 7,
"parentID": 0,
"Phone": "(896) 297-6568",
"City": "Louvain-la-Neuve",
"Name": "Celeste"
}, {
"ID": 8,
"parentID": 5,
"Phone": "(168) 452-3538",
"City": "Worksop",
"Name": "Rowan"
}, {
"ID": 9,
"parentID": 5,
"Phone": "(873) 337-9560",
"City": "Bad Neuenahr-Ahrweiler",
"Name": "Kendall"
}, {
"ID": 10,
"parentID": 0,
"Phone": "(450) 579-0491",
"City": "MIDdelburg",
"Name": "Madaline"
}, {
"ID": 11,
"parentID": 0,
"Phone": "(111) 162-2502",
"City": "Birecik",
"Name": "Chandler"
}, {
"ID": 12,
"parentID": 8,
"Phone": "(712) 483-3905",
"City": "Courbevoie",
"Name": "Craig"
}, {
"ID": 13,
"parentID": 8,
"Phone": "(872) 499-5833",
"City": "Cuccaro Vetere",
"Name": "Basia"
}, {
"ID": 14,
"parentID": 6,
"Phone": "(724) 797-0077",
"City": "Portree",
"Name": "Elmo"
}, {
"ID": 15,
"parentID": 5,
"Phone": "(366) 967-0433",
"City": "Dublin",
"Name": "Cairo"
}, {
"ID": 16,
"parentID": 11,
"Phone": "(147) 708-7321",
"City": "Rivière-du-Loup",
"Name": "Mannix"
}, {
"ID": 17,
"parentID": 0,
"Phone": "(407) 519-9894",
"City": "Roubaix",
"Name": "Justine"
}]
.
.
.
I wanted to make a treeview of this data and I got a result like the one below. No problem, it works properly.
[
{
"ID": 1,
"parentID": 0,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
},
{
"ID": 2,
"parentID": 0,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet",
"children": [
{
"ID": 30,
"parentID": 2,
"Phone": "(641) 756-7073",
"City": "Harrison Hot Springs",
"Name": "Hamilton",
"children": [
{
"ID": 54,
"parentID": 30,
"Phone": "(800) 876-5942",
"City": "Ribnitz-Damgarten",
"Name": "Kelsie",
"children": [
{
"ID": 62,
"parentID": 54,
"Phone": "(523) 159-2911",
"City": "Biała Podlaska",
"Name": "Clio"
}
]
},
{
"ID": 87,
"parentID": 30,
"Phone": "(500) 895-9220",
"City": "Piracicaba",
"Name": "Maya"
}
]
},
{
"ID": 40,
"parentID": 2,
"Phone": "(921) 336-7339",
"City": "Namur",
"Name": "Lionel"
},
{
"ID": 43,
"parentID": 2,
"Phone": "(410) 695-8540",
"City": "Saint-Laurent",
"Name": "Deanna",
"children": [
{
"ID": 63,
"parentID": 43,
"Phone": "(475) 190-5102",
"City": "Nicoya",
"Name": "Nola"
},
{
"ID": 98,
"parentID": 43,
"Phone": "(268) 572-5059",
"City": "San Marcello Pistoiese",
"Name": "Marny"
}
]
}
]
},
{
"ID": 3,
"parentID": 0,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria",
"children": [
{
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes",
"children": [
{
"ID": 44,
"parentID": 4,
"Phone": "(287) 866-8953",
"City": "Fiuminata",
"Name": "Darius",
"children": [
{
"ID": 47,
"parentID": 44,
"Phone": "(779) 411-0381",
"City": "Pontedera",
"Name": "Harding",
"children": [
{
"ID": 92,
"parentID": 47,
"Phone": "(925) 263-0254",
"City": "Curacaví",
"Name": "Aristotle"
}
]
}
]
},
{
"ID": 56,
"parentID": 4,
"Phone": "(963) 719-2718",
"City": "Gore",
"Name": "Rafael"
}
]
},
{
"ID": 58,
"parentID": 3,
"Phone": "(464) 318-7548",
"City": "Curepto",
"Name": "Leila"
}
]
.
.
.
My main question is parentID: I don't want to write parentID to objects that write 0. But when I remove the places that say parentID: 0, it doesn't work properly. Can you help?
The code I run is:
tree = function(array) {
var o = {
ID: 0
}
function arrGet(o) {
if (Array.isArray(o.children)) {
o.children.forEach(arrGet);
}
}
array.forEach(function(a) {
o[a.ID] = o[a.ID] || {
ID: a.ID,
parentID: a.parentID,
Phone: a.Phone,
City: a.City,
Name: a.Name
};
a.children = o[a.ID].children;
o[a.parentID] = o[a.parentID] || {
ID: a.parentID
};
o[a.parentID].children = o[a.parentID].children || [];
o[a.parentID].children.push(o[a.ID]);
});
arrGet(o[0]);
return o[0].children;
}(arr);
document.writeln('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
just find the way inside the tree, based on origin array...
Full code:
/*--------------------------------------------------------*\
| treeMaker : JSON [Array of obj] to Treeview (function) |
| |
| input array objets must be like { ID,[ parentID ] ...} |
\* -------------------------------------------------------*/
const treeMaker = arr =>
arr.reduce((tree,{parentID,...useful},_,Origin)=>
{
if (!parentID) tree.push({...useful}) // direct case!
else
{
let path = { children: tree } // path for insert
, road = [ Origin.find(x=>x.ID===parentID) ] // every road has an end
;
while(!!road[0].parentID) // as long as a parentID property exist
{
road.unshift(Origin.find(x=>x.ID===road[0].parentID)) // get road origin
}
for(let way of road) // make your way by following the road
{
path = path.children.find(x=>x.ID===way.ID) // change the path to children
}
if (!path.children) path.children = [] // if not exist, add children array
;
path.children.push({...useful}) // copy all useful items
}
return tree // back to the trees!
},[])
/*--------------------------------------------------------*/
// test part
const myArr =
[ { ID: 1, Phone: '(403) 125-2552', City: 'Coevorden', Name: 'Grady' }
, { ID: 2, Phone: '(979) 486-1932', City: 'Chełm', Name: 'Scarlet' }
, { ID: 3, Phone: '(573) 685-8350', City: 'Wardha', Name: 'Adria' }
, { ID: 4, parentID: 3, Phone: '(630) 292-9737', City: 'Villers-la-Loue', Name: 'Xerxes' }
, { ID: 5, Phone: '(755) 968-6539', City: 'Gönen', Name: 'Madeson' }
, { ID: 6, parentID: 5, Phone: '(644) 892-5485', City: 'Timkur', Name: 'Rae' }
, { ID: 7, Phone: '(896) 297-6568', City: 'Louvain-la-Neuve', Name: 'Celeste' }
, { ID: 8, parentID: 5, Phone: '(168) 452-3538', City: 'Worksop', Name: 'Rowan' }
, { ID: 9, parentID: 5, Phone: '(873) 337-9560', City: 'Bad Neuenahr-Ahrweiler', Name: 'Kendall' }
, { ID: 10, Phone: '(450) 579-0491', City: 'MIDdelburg', Name: 'Madaline' }
, { ID: 11, Phone: '(111) 162-2502', City: 'Birecik', Name: 'Chandler' }
, { ID: 12, parentID: 8, Phone: '(712) 483-3905', City: 'Courbevoie', Name: 'Craig' }
, { ID: 13, parentID: 8, Phone: '(872) 499-5833', City: 'Cuccaro Vetere', Name: 'Basia' }
, { ID: 14, parentID: 6, Phone: '(724) 797-0077', City: 'Portree', Name: 'Elmo' }
, { ID: 15, parentID: 5, Phone: '(366) 967-0433', City: 'Dublin', Name: 'Cairo' }
, { ID: 16, parentID: 11, Phone: '(147) 708-7321', City: 'Rivière-du-Loup', Name: 'Mannix' }
, { ID: 17, Phone: '(407) 519-9894', City: 'Roubaix', Name: 'Justine' }
, { ID: 18, parentID: 14, Phone: '(938) 793-5446', City: 'Eugene', Name: 'Dahlia' }
, { ID: 19, parentID: 5, Phone: '(425) 682-2189', City: 'Salisbury', Name: 'Irene' }
, { ID: 20, parentID: 12, Phone: '(351) 187-8200', City: 'Garaguso', Name: 'Trevor' }
, { ID: 21, Phone: '(601) 944-5214', City: 'Pointe-au-Pic', Name: 'Iris' }
, { ID: 22, parentID: 20, Phone: '(479) 532-6127', City: 'Salt Lake City', Name: 'Fleur' }
, { ID: 23, parentID: 19, Phone: '(339) 973-1695', City: 'Meldert', Name: 'Hayley' }
, { ID: 24, parentID: 11, Phone: '(946) 766-1649', City: 'Corral', Name: 'Baker' }
, { ID: 25, Phone: '(964) 413-7033', City: 'Joliet', Name: 'Leo' }
, { ID: 26, parentID: 7, Phone: '(898) 476-0059', City: 'Burntisland', Name: 'Rigel' }
]
const myTree = treeMaker ( myArr )
document.write('<pre>myTree:\n')
document.write(JSON.stringify(myTree,0,2))
document.write('</pre>')
In this algorithm, the destructuring assignment is used on each element of the original table, as follows:
let element1 = { ID:6, parentID:5, City:'Timkur', Name:'Rae' }
let {parentID, ...useful} = element1 // destructuring assignment
console.log( parentID ) // return 5
console.log( useful ) // return object { ID:6, City:'Timkur', Name:'Rae' }
console.log ( !parentID ) // return false
without parentID property:
let element2 = { ID:7, City:'Louvain-la-Neuve', Name: 'Celeste' }
let {parentID, ...useful} = element2 // destructuring assignment
console.log( parentID ) // undefined
console.log( useful ) // return object { ID:7, ....
console.log ( !parentID ) // return true
In this code the destructuring assignment is directly used inside the argument list of the array method reduce (see further)
About the use of the Array.reduce method (see mdn for more details):
const arr_tree = arr.reduce(function(tree,curr,idx,Origin) {…}, initilial_tree);
same as arrow notation:
a) const arr_tree = arr.reduce((tree,curr,_,Origin)=>{…}, []);
b) const arr_tree = arr.reduce((tree,{parentID,...useful},_,Origin)=>
Arrguments:
tree, array under construction (initialized by initilial_tree, here=[] =>empty array), this element must be returned at each iteration
curr: the current element (as in a loop on the array), **used in an destructuring assignment
{parentID,...useful} = curr ( please compare a) and b) )
idx: the index of the element (curr) on the array (not useful here and replaced by _)
Origin: the original table used by the method
the algorithm:
for any element with a parentID, its parent must be found in the tree under construction.
That is, for an X element with a parentID there is an X-1 element with that ID.
And if this X-1 element has itself a ParentID, there is also another X-2 element with this ID.
And so on, until we find an X-n element that has no ParentID.
This X-N element is directly at the root of the result array.
All that remains is to follow the reverse path in the tree structure under construction:
we look for the position Xn at the level of its root, then on this one the element X- (n-1) among its children, until finding that of the element X-1 where we can add the element X in the list of its children.
Making sure to add an empty list of children, if X-1 had no children yet.
There are therefore 2 parts:
1- go up the road from X-1 to the X-n elements using the origin table
let road = [ Origin.find(x=>x.ID===parentID) ] // every road has an end
while(!!road[0].parentID) // as long as a parentID property exist
{
road.unshift(Origin.find(x=>x.ID===road[0].parentID)) // get road origin
}
if we start from element X = { ID: 12, parentID: 8, ... Name: 'Craig'} (where the parentID value is 8)
the result is :
road = [ { ID: 5, ... Name: 'Madeson' }
, { ID: 8, parentID: 5,... Name: 'Rowan' }
]
note 1:
the use of the array.unshift() method to add the elements from the top
/ unlike the array.push() method, the last element entered is therefore in position zero,
which allows the test to be passed
(!!road[0].parentID)
with always an index value at zero.
...For the double exclamation mark look here
note 2:
the road array only contains "pointers" to the objects of the original array.
2- find the path of element X-1 in tree structure under construction
let path = { children: tree } // path for insert
for(let way of road) // make your way by following the road
{
path = path.children.find(x=>x.ID===way.ID) // change the path to children
}
note X: I use my sort of Whitesmiths style code formatting for years
for info, it's look like that:
├─1_Grady
├─2_Scarlet
├─3_Adria─┐
│ └─4_Xerxes
├─5_Madeson─┐
│ ├─6_Rae─┐
│ │ └─14_Elmo─┐
│ │ └─18_Dahlia
│ ├─8_Rowan─┐
│ │ ├─12_Craig─┐
│ │ │ └─20_Trevor─┐
│ │ │ └─22_Fleur
│ │ └─13_Basia
│ ├─9_Kendall
│ ├─15_Cairo
│ └─19_Irene─┐
│ └─23_Hayley
├─7_Celeste─┐
│ └─26_Rigel
├─10_Madaline
├─11_Chandler─┐
│ ├─16_Mannix
│ └─24_Baker
├─17_Justine
├─21_Iris
└─25_Leo
What you can do is to use the delete operator when parentID is equal to 0. This will delete the property from the object, hence not displaying it.
var arr = [{
"ID": 1,
"parentID": 0,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
}, {
"ID": 2,
"parentID": 0,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet"
}, {
"ID": 3,
"parentID": 0,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria"
}, {
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes"
}, {
"ID": 5,
"parentID": 0,
"Phone": "(755) 968-6539",
"City": "Gönen",
"Name": "Madeson"
}, {
"ID": 6,
"parentID": 5,
"Phone": "(644) 892-5485",
"City": "Timkur",
"Name": "Rae"
}, {
"ID": 7,
"parentID": 0,
"Phone": "(896) 297-6568",
"City": "Louvain-la-Neuve",
"Name": "Celeste"
}, {
"ID": 8,
"parentID": 5,
"Phone": "(168) 452-3538",
"City": "Worksop",
"Name": "Rowan"
}, {
"ID": 9,
"parentID": 5,
"Phone": "(873) 337-9560",
"City": "Bad Neuenahr-Ahrweiler",
"Name": "Kendall"
}, {
"ID": 10,
"parentID": 0,
"Phone": "(450) 579-0491",
"City": "MIDdelburg",
"Name": "Madaline"
}, {
"ID": 11,
"parentID": 0,
"Phone": "(111) 162-2502",
"City": "Birecik",
"Name": "Chandler"
}, {
"ID": 12,
"parentID": 8,
"Phone": "(712) 483-3905",
"City": "Courbevoie",
"Name": "Craig"
}, {
"ID": 13,
"parentID": 8,
"Phone": "(872) 499-5833",
"City": "Cuccaro Vetere",
"Name": "Basia"
}, {
"ID": 14,
"parentID": 6,
"Phone": "(724) 797-0077",
"City": "Portree",
"Name": "Elmo"
}, {
"ID": 15,
"parentID": 5,
"Phone": "(366) 967-0433",
"City": "Dublin",
"Name": "Cairo"
}, {
"ID": 16,
"parentID": 11,
"Phone": "(147) 708-7321",
"City": "Rivière-du-Loup",
"Name": "Mannix"
}, {
"ID": 17,
"parentID": 0,
"Phone": "(407) 519-9894",
"City": "Roubaix",
"Name": "Justine"
}];
tree = function(array) {
var o = {
ID: 0
}
function arrGet(o) {
if (Array.isArray(o.children)) {
o.children.forEach(arrGet);
}
}
array.forEach(function(a) {
o[a.ID] = o[a.ID] || {
ID: a.ID,
parentID: a.parentID,
Phone: a.Phone,
City: a.City,
Name: a.Name
};
if(a.parentID === 0)
delete o[a.ID].parentID;
a.children = o[a.ID].children;
o[a.parentID] = o[a.parentID] || {
ID: a.parentID
};
o[a.parentID].children = o[a.parentID].children || [];
o[a.parentID].children.push(o[a.ID]);
});
arrGet(o[0]);
return o[0].children;
}(arr);
document.writeln('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
var arr = [{
"ID": 1,
"Phone": "(403) 125-2552",
"City": "Coevorden",
"Name": "Grady"
}, {
"ID": 2,
"Phone": "(979) 486-1932",
"City": "Chełm",
"Name": "Scarlet"
}, {
"ID": 3,
"Phone": "(573) 685-8350",
"City": "Wardha",
"Name": "Adria"
}, {
"ID": 4,
"parentID": 3,
"Phone": "(630) 292-9737",
"City": "Villers-la-Loue",
"Name": "Xerxes"
}, {
"ID": 5,
"Phone": "(755) 968-6539",
"City": "Gönen",
"Name": "Madeson"
}, {
"ID": 6,
"parentID": 5,
"Phone": "(644) 892-5485",
"City": "Timkur",
"Name": "Rae"
}, {
"ID": 7,
"Phone": "(896) 297-6568",
"City": "Louvain-la-Neuve",
"Name": "Celeste"
}, {
"ID": 8,
"parentID": 5,
"Phone": "(168) 452-3538",
"City": "Worksop",
"Name": "Rowan"
}, {
"ID": 9,
"parentID": 5,
"Phone": "(873) 337-9560",
"City": "Bad Neuenahr-Ahrweiler",
"Name": "Kendall"
}, {
"ID": 10,
"Phone": "(450) 579-0491",
"City": "MIDdelburg",
"Name": "Madaline"
}, {
"ID": 11,
"Phone": "(111) 162-2502",
"City": "Birecik",
"Name": "Chandler"
}, {
"ID": 12,
"parentID": 8,
"Phone": "(712) 483-3905",
"City": "Courbevoie",
"Name": "Craig"
}, {
"ID": 13,
"parentID": 8,
"Phone": "(872) 499-5833",
"City": "Cuccaro Vetere",
"Name": "Basia"
}, {
"ID": 14,
"parentID": 6,
"Phone": "(724) 797-0077",
"City": "Portree",
"Name": "Elmo"
}, {
"ID": 15,
"parentID": 5,
"Phone": "(366) 967-0433",
"City": "Dublin",
"Name": "Cairo"
}, {
"ID": 16,
"parentID": 11,
"Phone": "(147) 708-7321",
"City": "Rivière-du-Loup",
"Name": "Mannix"
}, {
"ID": 17,
"Phone": "(407) 519-9894",
"City": "Roubaix",
"Name": "Justine"
}, {
"ID": 18,
"parentID": 14,
"Phone": "(938) 793-5446",
"City": "Eugene",
"Name": "Dahlia"
}, {
"ID": 19,
"parentID": 5,
"Phone": "(425) 682-2189",
"City": "Salisbury",
"Name": "Irene"
}, {
"ID": 20,
"parentID": 12,
"Phone": "(351) 187-8200",
"City": "Garaguso",
"Name": "Trevor"
}, {
"ID": 21,
"Phone": "(601) 944-5214",
"City": "Pointe-au-Pic",
"Name": "Iris"
}, {
"ID": 22,
"parentID": 20,
"Phone": "(479) 532-6127",
"City": "Salt Lake City",
"Name": "Fleur"
}, {
"ID": 23,
"parentID": 19,
"Phone": "(339) 973-1695",
"City": "Meldert",
"Name": "Hayley"
}, {
"ID": 24,
"parentID": 11,
"Phone": "(946) 766-1649",
"City": "Corral",
"Name": "Baker"
}, {
"ID": 25,
"Phone": "(964) 413-7033",
"City": "Joliet",
"Name": "Leo"
}, {
"ID": 26,
"parentID": 7,
"Phone": "(898) 476-0059",
"City": "Burntisland",
"Name": "Rigel"
}]
original data like this

How to extract multiple array of objects from Json data containing multiple array of objects?

I have a Json data which contains multiple array of objects sends by mvc controller. I need to extract those array differently. I want getEmailBasicData array, getEmailParticipantData array, getEmailDocumentData array individually How can I do that? Here is my code-
"{
"$id": "1",
"getEmailBasicData": [
{
"$id": "2",
"notificationId": 23,
"subject": "final test",
"message": "<p>this is body</p>\n",
"sendStatus": -1,
"lastSendTime": null
},
{
"$id": "3",
"notificationId": 24,
"subject": "final subject",
"message": "<p>final body</p>\n",
"sendStatus": -1,
"lastSendTime": null
},
{
"$id": "12",
"notificationId": 33,
"subject": "Final Test",
"message": "<p>Final body</p>\n",
"sendStatus": -1,
"lastSendTime": null
}
],
"getEmailParticipantData": [
{
"$id": "13",
"id": 55,
"notificationId": 23,
"employeeId": -1,
"name": "here is the name",
"emailAddress": "whatever#gmail.com",
"contactNo": null
},
{
"$id": "14",
"id": 56,
"notificationId": 23,
"employeeId": -1,
"name": "another name",
"emailAddress": "someone#gmail.com",
"contactNo": null
} ],
"getEmailDocumentData": [
{
"$id": "36",
"id": 40,
"notificationId": 23,
"docId": 1,
"attachmentLocation": "1_1_50474603_2287746231437248_8529393497499762688_n.jpg"
},
{
"$id": "46",
"id": 50,
"notificationId": 33,
"docId": 1,
"attachmentLocation":
"1_1_50474603_2287746231437248_8529393497499762688_n.jpg"
}
]
}"
You can use destructuring assignment
let obj = {"$id":"1","getEmailBasicData":[{"$id":"2","notificationId":23,"subject":"finaltest","message":"<p>thisisbody</p>\n","sendStatus":-1,"lastSendTime":null},{"$id":"3","notificationId":24,"subject":"finalsubject","message":"<p>finalbody</p>\n","sendStatus":-1,"lastSendTime":null},{"$id":"12","notificationId":33,"subject":"FinalTest","message":"<p>Finalbody</p>\n","sendStatus":-1,"lastSendTime":null}],"getEmailParticipantData":[{"$id":"13","id":55,"notificationId":23,"employeeId":-1,"name":"MdRashedulIslam","emailAddress":"rashed.cse08#gmail.com","contactNo":null},{"$id":"14","id":56,"notificationId":23,"employeeId":-1,"name":"Akash","emailAddress":"akash#ravensystemstld.com","contactNo":null}],"getEmailDocumentData":[{"$id":"36","id":40,"notificationId":23,"docId":1,"attachmentLocation":"1_1_50474603_2287746231437248_8529393497499762688_n.jpg"},{"$id":"46","id":50,"notificationId":33,"docId":1,"attachmentLocation":"1_1_50474603_2287746231437248_8529393497499762688_n.jpg"}]}
const {getEmailBasicData,getEmailDocumentData,getEmailParticipantData} = obj
console.log(getEmailBasicData,getEmailDocumentData,getEmailParticipantData)
Use the . operator to access
var a={
"$id": "1",
"getEmailBasicData": [
{
"$id": "2",
"notificationId": 23,
"subject": "final test",
"message": "<p>this is body</p>\n",
"sendStatus": -1,
"lastSendTime": null
},
{
"$id": "3",
"notificationId": 24,
"subject": "final subject",
"message": "<p>final body</p>\n",
"sendStatus": -1,
"lastSendTime": null
},
{
"$id": "12",
"notificationId": 33,
"subject": "Final Test",
"message": "<p>Final body</p>\n",
"sendStatus": -1,
"lastSendTime": null
}
],
"getEmailParticipantData": [
{
"$id": "13",
"id": 55,
"notificationId": 23,
"employeeId": -1,
"name": "Md Rashedul Islam",
"emailAddress": "rashed.cse08#gmail.com",
"contactNo": null
},
{
"$id": "14",
"id": 56,
"notificationId": 23,
"employeeId": -1,
"name": "Akash",
"emailAddress": "akash#ravensystemstld.com",
"contactNo": null
} ],
"getEmailDocumentData": [
{
"$id": "36",
"id": 40,
"notificationId": 23,
"docId": 1,
"attachmentLocation": "1_1_50474603_2287746231437248_8529393497499762688_n.jpg"
},
{
"$id": "46",
"id": 50,
"notificationId": 33,
"docId": 1,
"attachmentLocation":
"1_1_50474603_2287746231437248_8529393497499762688_n.jpg"
}
]
}
var basic=a.getEmailBasicData;
var doc=a.getEmailDocumentData;
var participants=a.getEmailParticipantData;
console.log(basic);
console.log(doc);
console.log(participants);

How to get specific data from a list of JSON

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()

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