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

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.

Related

change value based on nested array value

I got a below object from the API
let response = {
"id": 301344576,
"quantity": 92,
"unlimited": false,
"inStock": true,
"name": "Virgin Coconut Oil",
"price": 328.47,
"isShippingRequired": true,
"weight": 0.5,
"url": "https://subhikshaf2c.company.site/Virgin-Coconut-Oil-p301344576",
"options": [
{
"type": "SELECT",
"name": "Weight",
"nameTranslated": {
"en": "Weight"
},
"choices": [
{
"text": "500 gm",
"textTranslated": {
"en": "500 gm"
},
"priceModifier": 0,
"priceModifierType": "ABSOLUTE"
},
{
"text": "1 kg",
"textTranslated": {
"en": "1 kg"
},
"priceModifier": 317.03,
"priceModifierType": "ABSOLUTE"
}
],
"defaultChoice": 0,
"required": false
}
],
"combinations": [
{
"id": 161026822,
"combinationNumber": 1,
"options": [
{
"name": "Weight",
"nameTranslated": {
"en": "Weight"
},
"value": "1 kg",
"valueTranslated": {
"en": "1 kg"
}
}
],
"sku": "OL002-001592-1kg",
"quantity": 36,
"inStock": true,
"unlimited": false,
"weight": 1,
"warningLimit": 20,
"attributes": [],
"defaultDisplayedPrice": 677.78,
"defaultDisplayedPriceFormatted": "₹677.78"
}
]
}
and the weight info of this. Suppose i got 1KG so i'm creating JSON like
{
"Id":301344576,
"weight":"1 kg",
"quantity":1
}
In another page again I'm calling the same API and need to create json format like
[
{
"stock": 92,
"quantity": 1,
"productId": 301344576,
"basePrice": 328.47,
"productPrice": 344.89,
"weight": "500 gm",
"productName": "Virgin Coconut Oil",
}
]
The problem is if the weight: '1KG' i need to look into the combinations and need to update the quantity. So my json will become like
{
"stock": 36,
"quantity": 1,
"productId": 301344576,
"basePrice": 645.5,
"productPrice": 344.89,
"weight": "1 kg",
"productName": "Virgin Coconut Oil",
}
for the basePrice, I'm doing price+priceModifier value of selected weight from the options.
How can i achieve the desired result.

How do I use Object.entries(...).forEach.every?

I'm filtering a list using a const queryModifier = {price: "lessThan", weight: "greaterThan"}
const queryKeys = keys: {
price: '1000',
weight: '1000'
}
const list = [
{
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-11-05 10:48:18",
"createdBy": "test#test.com",
"deliveryDate": "2019-11-08 10:46:37",
"driver": "",
"dropOff": "Kögel Trailer GmbH & Co. KG, Am Kögel-Werk, Burtenbach, Germany",
"height": 0,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "7e249529-d089-47bb-b0ad-470f850dd8cf",
"notes": "",
"orderId": "",
"pickUp": "Altenberge, Germany",
"price": 500,
"quantity": 1,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "engl. Anschlüsse",
"vehicleId": "505123",
"vehicleReadyDate": "2019-11-05 10:47:57",
"weight": 0
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-10-14 16:32:12",
"createdBy": "test#test.com",
"deliveryDate": "2019-10-19 16:26:35",
"driver": "",
"dropOff": "Marville-Moutiers-Brûlé, France",
"height": 600,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "9b7f57fd-f95e-4038-b120-a0301fdf3f31",
"notes": "",
"orderId": "",
"pickUp": "Altenberge, Germany",
"price": 0,
"quantity": 1,
"trailer": "2er Pack",
"vehicle": "Anhänger",
"vehicleClass": "50",
"vehicleId": "123",
"vehicleReadyDate": "2019-10-16 16:31:26",
"weight": 12000
},
{
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-10-14 16:25:54",
"createdBy": "test#test.com",
"deliveryDate": "2019-10-19 16:24:13",
"driver": "",
"dropOff": "Vendenheim, France",
"height": 0,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "7e4f233f-695b-40eb-a0ca-fd78f3fa43cd",
"notes": "",
"orderId": "",
"pickUp": "Altenberge, Germany",
"price": 793,
"quantity": 1,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "Standard",
"vehicleId": "3340731",
"vehicleReadyDate": "2019-10-15 16:24:58",
"weight": 0
},
{
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-26 18:32:18",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-20 18:31:45",
"driver": "Michal Kucharski",
"dropOff": "Logroño, Spain",
"height": 0,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "388113f5-3927-4fe3-80d5-f2fcf1c7cedd",
"notes": "",
"orderId": "",
"pickUp": "16671 Butano Place, Fontana, CA, USA",
"price": 0,
"quantity": 1,
"trailer": "2er Pack",
"vehicle": "Sattel",
"vehicleClass": "Standard",
"vehicleId": "efgefg",
"vehicleReadyDate": "2019-09-27 18:32:08",
"weight": 0
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-06 22:57:55",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-07 22:57:03",
"driver": "Eugeniusz Galinski",
"dropOff": "12345 Lamplight Village Avenue, Austin, TX, USA",
"height": 32,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "ac3cf14e-b43b-45e4-9168-ad4997b6415d",
"notes": "Nzube I am adding notes here",
"pickUp": "16671 Butano Place, Fontana, CA, USA",
"price": 100,
"quantity": 3,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "Mega",
"vehicleId": "123",
"vehicleReadyDate": "2019-09-26 22:57:36",
"weight": 12
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-06 22:46:25",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-06 22:45:45",
"driver": "Michal Kucharski",
"dropOff": "QEW, Niagara Falls, ON, Canada",
"height": 67,
"isPreparingTrailer": false,
"isSmsSent": false,
"isTrailerReady": false,
"key": "d0ec3b82-2279-4d11-8e35-a9307713ae5a",
"notes": "This is coming along",
"pickUp": "Avenida Callao 1234, Buenos Aires, Argentina",
"price": 100,
"quantity": 1,
"trailer": "2er Pack",
"vehicle": "Sattel",
"vehicleClass": "Mega",
"vehicleId": "123",
"vehicleReadyDate": "2019-09-25 22:45:57",
"weight": 12
},
{
"additionalPrices": 0,
"clientOrderNumber": "N / A",
"companyName": "Test Company",
"createdAt": "2019-09-04 18:06:18",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-05 18:05:51",
"driver": "Chibuzo ilogu",
"dropOff": "Asda Park Royal Superstore, Western Road, London, UK",
"height": 453,
"isPreparingTrailer": true,
"isSmsSent": true,
"isTrailerReady": true,
"key": "96ee9410-4d70-4bbc-8016-5d7c9e5ecec1",
"notes": "ewriupoi ",
"pickUp": "Avenida Juan Bautista Alberdi 1233, Buenos Aires, Argentina",
"price": 234,
"quantity": 1,
"trailer": "3er Pack",
"vehicle": "Anhänger",
"vehicleClass": "50",
"vehicleId": "543",
"vehicleReadyDate": "2019-09-21 18:06:03",
"weight": 453
},
{
"additionalPrices": 0,
"companyName": "Test Company",
"completeDate": "2019-09-04 18:02:27",
"createdAt": "2019-09-04 18:01:30",
"createdBy": "test#test.com",
"deliveryDate": "2019-09-04 18:01:09",
"driver": "Chibuzo ilogu",
"dropOff": "La Cabaña 123, Las Condes, Chile",
"height": 123,
"isPreparingTrailer": false,
"isSmsSent": true,
"isTrailerReady": true,
"key": "bcd50f43-0644-49a7-8bdc-009a4572341b",
"notes": "qewqe",
"pickUp": "La Cabaña 123, Las Condes, Chile",
"price": 123,
"trailer": "einzeln",
"vehicle": "Sattel",
"vehicleClass": "Standard",
"vehicleId": "123",
"vehicleReadyDate": "2019-10-02 18:01:19",
"weight": 123
}
];
export const handleFilterModifier = (value, compareValue, modifier) => {
if (modifier === 'lessThan') {
return value > compareValue;
}
if (modifier === 'equals') {
return value === compareValue;
}
if (modifier === 'greaterThan') {
return value < compareValue;
}
return null;
};
const resultList = list.filter(
item => Object.entries(queryModifiers).every(([filterKey, filterVal]) => {
const compareValue = item[filterKey];
const value = Object.values(queryKeys);
const result = handleFilterModifier(
parseFloat(value),
compareValue,
filterVal
);
return result;
})
);
This operation fails when either of the queryModifiers has "equals" in its value pair. Anything else returns the actual true result. I don't understand why it fails on "equals".
I feel like there should be a forEach somewhere but I don't know where to put it and maybe there's something wrong with the code. I need help figuring it out.
I think you should replace this
const queryKeys = keys: {
price: '1000',
weight: '1000'
}
with
const queryKeys = {
price: '1000',
weight: '1000'
}
and replace this
const value = Object.values(queryKeys);
with
const value = queryKeys[filterKey];

Parsing json string to an array

What i need to do here is whenever i call a method say for campaign data it needs to go to "name" : "campaign " and give me "values" in this format
{"car":"car",
"bus":"bus",
"truck":"truck",
"train":"train"}
in the same way i need for sub campaign . (Comment if anything is unclear)
{
"fields": [
{
"name": "campaign",
"default": "",
"values": [
"car",
"bus",
"truck",
"train"
]
},
{
"name": "subCampaign",
"default": "",
"values": [
"Spring 2015",
"BTS 2015",
"BTS 2014",
"Holiday 2015",
"Holiday 2014"
]
},
]
}
If we have
var obj ={
"fields": [
{
"name": "campaign",
"default": "",
"values": [
"car",
"bus",
"truck",
"train"
]
},
{
"name": "subCampaign",
"default": "",
"values": [
"Spring 2015",
"BTS 2015",
"BTS 2014",
"Holiday 2015",
"Holiday 2014"
]
},
]
};
You can do it like this, say for `campaign, you can use:
var result = {};
obj.fields[0].values.forEach(function(val){
result[val] = val
});
This would give result as object having value : {car: "car", bus: "bus", truck: "truck", train: "train"}
Assuming you want {"car":"car", "bus":"bus","truck":"truck","train":"train"}
var object = {
"fields": [{
"name": "campaign",
"default": "",
"values": [
"car",
"bus",
"truck",
"train"]
},
{
"name": "subCampaign",
"default": "",
"values": [
"Spring 2015",
"BTS 2015",
"BTS 2014",
"Holiday 2015",
"Holiday 2014"]
}, ]
};
var passingObj = object.fields[0].values;
alert(JSON.stringify(getObj(passingObj)));
function getObj(passingObj) {
var obj = {};
for (var index in passingObj) {
obj[passingObj[index]] = passingObj[index];
}
return obj;
}

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