Getting values from JSON multidimensional array? - javascript

I have a JSON array that looks like this:
{
"id": 258,
"rawId": null,
"displayName": null,
"name": {
"givenName": "my ame",
"honorificSuffix": "",
"formatted": "my ame",
"middleName": "",
"familyName": "",
"honorificPrefix": ""
},
"nickname": "",
"phoneNumbers": [{
"value": "23423442342424",
"pref": false,
"id": 0,
"type": "mobile"
}],
"emails": null,
"addresses": null,
"ims": null,
"organizations": [{
"pref": "false",
"title": "",
"name": "",
"department": "",
"type": null
}],
"birthday": null,
"note": "",
"photos": null,
"categories": null,
"urls": null
}
I need to get the phoneNumbers >> value from this JSON.
SO I TRIED SOMETHING LIKE THIS:
var d = JSON.parse(test);
alert(test[0].phoneNumbers.value);
The variable test is the JSON shown above.
and I also tried:
alert(d[0].phoneNumbers.value);
and
alert(test.phoneNumbers.value);
But none of the above work.
Is there something that I am missing in my code?
Thanks in advance.

What you showed us is a JSON string (giving a JS object after parsing), not an array.
So d[0].phoneNumbers will not work and d.phoneNumbers will work and will give you an array.
And because it will give you an array, d.phoneNumbers.value will not work, and d.phoneNumbers[0].value will.

Related

Advice for deeply nested filtering with nested object for RXJS in angular?

Quick Question:
Pardon me, I'm fairly new to Typescipt & RxJS. I have the following JSON:
[
{
"ID": "",
"UEN": "",
"Name": "",
"Address": "",
"Telephone": "",
"Fax": "",
"Email": "",
"Website": "",
"Postal": "",
"Status": ,
"TimeCreated": ,
"TimeUpdated": ,
"Workheads": [{
"ID": "",
"Name": "",
"Code": ""
},
{
"ID": "",
"Name": "",
"Code": ""
}
]
},
...
]
This json is feed into my angular app via Observable from HTTP get().
How do I filter the workhead.Code section such that I could get those relevant Json objects within the array by matching the inner workhead.Code to a specific string that has been provided by the user (e.g. workhead.Code == 'CS2230')?
Help appreciated.
You are not clear exactly what you want returned. I assume you want the full objects returned, and not only the inner "Workheads". You can use a filter() to get what you want:
const data = [{
"ID": "",
"UEN": "",
"Name": "",
"Address": "",
"Telephone": "",
"Fax": "",
"Email": "",
"Website": "",
"Postal": "",
"Status": "",
"TimeCreated": "",
"TimeUpdated": "",
"Workheads": [{
"ID": "",
"Name": "",
"Code": "abc"
}, {
"ID": "",
"Name": "",
"Code": "def"
}]
}];
// Returns an array of the objects which contain matching code.
const getRelatedByCode = (arr, userProvidedCode) => {
return arr.filter((i) => {
return (i.Workheads || [])
.some(wh => wh.Code === userProvidedCode);
});
}
console.log(getRelatedByCode(data, 'abc')); // Returns array with the object
console.log(getRelatedByCode(data, 'zzz')); // Returns empty array

serialize javascript array of object with nested arrays

Good day! Could anyone suggest please, is it possible to serialize/unserialize array of object in JavaScript and do not lose nested arrays? I want to save it into the database but when I unserialize json I lose prices array.
I use JSON.stringify and JSON.parse.
const arr = [{
"HotSpotData": "<SchematicsDefinition><Schema2D><Rectangles><RectangleDefinition ZOrder=\"0\" Top=\"440\" Left=\"176\" Width=\"27\" Height=\"27\" ShapeType=\"2\"/></Rectangles></Schema2D></SchematicsDefinition>",
"Ptr": 24580100323769,
"Ptr": 24588687801988,
"Ptr": 24773374403522,
"Qty": 1,
"Desc": "",
"Ptr": 24588687801988,
"Reference": 1,
"id": 25,
"notes": "",
"Code": "1831001",
"Description": "REEL CARRIER ",
"Ptr": 24558623176188,
"Notice": "",
"Order": 1,
"PartImage": null,
"prices": [{
"pricePtr": 24648817311745,
"priceValue": 1970.9,
"priceCaption": "USD LIST",
"currency": "USD"
}],
"rnd_unic": 1597222193169
}]
console.log(JSON.parse(JSON.stringify(arr)))

How to use this json with angular datatables

This is my server response.
{
"status": "success",
"data": [{
"id": null,
"reportType": "Total Voucher Report",
"reportModule": "Vouchers",
"reportData": [{
"id": "1",
"voucherPackId": "2",
"serialNumber": "0",
"status": "Free",
"isBlocked": "N",
"voucherPin": "0",
"buyDate": null,
"redeemDate": null,
"phoneNumber": null,
"statusCode": null,
"identifier": "MCM0007532",
"merchantName": "test1",
"voucherName": "fddf",
"expiryDate": "2016-02-24 00:00:00",
"dealCategory": "Hotels \u0026 Travel",
"shortDescription": "xvxv",
"voucherWorth": "33.00"
}, {
"id": "2",
"voucherPackId": "2",
"serialNumber": "0",
"status": "Free",
"isBlocked": "N",
"voucherPin": "0",
"buyDate": null,
"redeemDate": null,
"phoneNumber": null,
"statusCode": null,
"identifier": "MCM0007532",
"merchantName": "test1",
"voucherName": "fddf",
"expiryDate": "2016-02-24 00:00:00",
"dealCategory": "Hotels \u0026 Travel",
"shortDescription": "xvxv",
"voucherWorth": "33.00"
}, {
"id": "3",
"voucherPackId": "2",
"serialNumber": "0",
"status": "Free",
"isBlocked": "N",
"voucherPin": "0",
"buyDate": null,
"redeemDate": null,
"phoneNumber": null,
"statusCode": null,
"identifier": "MCM0007532",
"merchantName": "test1",
"voucherName": "fddf",
"expiryDate": "2016-02-24 00:00:00",
"dealCategory": "Hotels \u0026 Travel",
"shortDescription": "xvxv",
"voucherWorth": "33.00"
}]
}],
"message": null}
I used it as,
vm.dtOptions = DTOptionsBuilder
.newOptions()
.withOption('ajax', {
url: config.base_url + 'report/voucher?module=Vouchers&type=Total Voucher Report&merchant=1',
type: 'POST',
dataSrc: 'data.data[0].reportData[0]',
})
.withOption('processing', true)
.withOption('serverSide', true)
.withBootstrap()
.withPaginationType('full_numbers');
It says invalid JSON response. Appreciate your kindly help.
Debug result: http://debug.datatables.net/urizon
Use the following value for dataSrc option: data[0].reportData as shown below. Also you need to remove serverSide and processing options since your data doesn't have correct structure for server-side processing mode.
You also need to define columns structure since you're using array of objects as your data source.
vm.dtOptions = DTOptionsBuilder
.newOptions()
.withOption('ajax', {
url: config.base_url + 'report/voucher?module=Vouchers&type=Total Voucher Report&merchant=1',
type: 'POST',
dataSrc: 'data[0].reportData'
})
.withBootstrap()
.withPaginationType('full_numbers');
vm.dtColumns = [
/* List data properties for each column in the table. */
DTColumnBuilder.newColumn('id'),
DTColumnBuilder.newColumn('voucherPackId'),
DTColumnBuilder.newColumn('serialNumber'),
DTColumnBuilder.newColumn('status')
];
If your use a parser your will get error : SyntaxError: JSON.parse: end of data after property value in object at line 63 column 16 of the JSON data. So yes your JSON is invalid ! Just add } on list line. Because every brackets need to be closed.
Make sure the JSON response has Content-Type: application/json header, otherwise it might not be parsed correctly.

Sorting Object by keys numerically with AngularJS

Ok, so I am trying to sort out my json data into a table:
{
"0": {
"1": {
"airdate": "2011-12-04",
"file_size": 368279154,
"location": "filepath",
"name": "episodename",
"quality": "Unknown",
"release_name": "",
"status": "Downloaded",
"subtitles": ""
}
},
"1": {
"1": {
"airdate": "2011-12-04",
"file_size": 368279154,
"location": "filepath",
"name": "episodename1",
"quality": "Unknown",
"release_name": "",
"status": "Downloaded",
"subtitles": ""
},
"2": {
"airdate": "2011-12-04",
"file_size": 368279154,
"location": "filepath",
"name": "episodename2",
"quality": "Unknown",
"release_name": "",
"status": "Downloaded",
"subtitles": ""
},
"14": {
"airdate": "2011-12-04",
"file_size": 368279154,
"location": "filepath",
"name": "episodename14",
"quality": "Unknown",
"release_name": "",
"status": "Downloaded",
"subtitles": ""
}
}
The problem is my angular ng-repeat lists it in order alphabetically ex 1, 14, 2... I can't seem to work with this object to take the key and set it as an ID parameter for the object but I thought that would be the best option. any suggestions would be helpful. I would like to note I cannot alter the server side api.
if the order of some collection is important, you should consider using array instead.
if you stick using object, the way is to create an array to keep the object's keys for orderfing purpose
the prototype
scope.obj = {"1":{}, "2":{}, "14":{}};
scope.objKeys = ['1', '2', '14'];
<div ng-repeat="key in objKeys">
{{obj[key]}}
</div>

how to return null composite objects in mql

I have been working on a simple calorie counter using freebase. When I am querying for a recipe I am not getting all the entries returned.
My query is:
[{
"id": "/m/0e cvb9k7",
"name": null,
"/food/recipe/ingredients": [{
"id": null,
"ingredient": {
"id": null,
"name": null,
"/food/food/energy": null
},
"unit": {
"id": null,
"name": null
},
"quantity": null
}]
}]
For example, in the gumbo recipe there are ingredients like onions or peppers where unit is null. Those are not returned by this query. How do I write a query that will return all the ingredients, including the ones with null units?
I tried:
"unit|=": [
null,
{
"id": null,
"name": null
}
]
This gave me an error Comparison operator |= takes a non-empty list of values.
Add "optional": true to that subquery viz
[{
"id": "/m/0e cvb9k7",
"name": null,
"/food/recipe/ingredients": [{
"id": null,
"ingredient": {
"id": null,
"name": null,
"/food/food/energy": null
},
"unit": {
"id": null,
"name": null
"optional":true
},
"quantity": null
}]
}]

Categories

Resources