Sorting Object by keys numerically with AngularJS - javascript

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>

Related

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

Getting values from JSON multidimensional array?

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.

Using underscore.js to find values in deeply nested JSON

I'm pretty new to Javascript, and I just learned about underscore.js. I have a deeply nested JSON object, and I need to use underscore to find key/value pairs, which I will then use to populate various HTML tables. If the structure was more shallow, using something like _.pluck would be easy, but I just don't know how to traverse past the first couple of nesting levels (i.e. surveyGDB, table, tablenames). The JSON object comes from an XML that is comprised of multiple nesting structures (mashed up from different database tables).
var JSONData =
"surveyGDB": {
"filename": "..\\Topo\\SurveyGeoDatabase.gdb",
"table": {
"tablename": [
{
"#text": "SurveyInfo\n ",
"record": {
"OBJECTID": "1",
"SiteID": "CBW05583-345970",
"Watershed": "John Day",
"VisitType": "Initial visit",
"SurveyInstrument": "Total Station",
"ImportDate": "2015-07-22T09:08:42",
"StreamName": "Duncan Creek",
"InstrumentModel": "TopCon Magnet v2.5.1",
"FieldSeason": "2015"
}
},
{
"#text": "QaQcPoints\n ",
"record": [
{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tp",
"Count": "357"
},
{
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tb",
"Count": "92"
},
{
"OBJECTID": "3",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "to",
"Count": "8"
},
{
"OBJECTID": "4",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bl",
"Count": "279"
},
{
"OBJECTID": "5",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bf",
"Count": "18"
}
]
},
{
"#text": "QaQcPolygons\n ",
"record": [
{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:43:08",
"SurveyExtentCount": "",
"WaterExtentCount": "",
"ChannelUnitsCount": "",
"ChannelUnitsUnique": ""
},
{
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T13:35:15",
"SurveyExtentCount": "1",
"WaterExtentCount": "1",
"ChannelUnitsCount": "21",
"ChannelUnitsUnique": "21"
}
]
}
]
}
}
}
For instance, I wanted all of the values for 'Code' in the 'QaQCPoints' table, so I tried:
var codes = _.flatten(_.pluck(JSONData.surveyGDB.table.tablename[1].record[0], "Code" ));
console.log(codes);
In the console, this returns an array with a length of 5, but with blank values.
What am I doing wrong?
I'd also rather search for the 'Code' values in the table based on something like the '#text' key value, instead of just using it's position in the object.
If I understood you correctly, you want to always search the record array within JSONData.surveyGDB.table.tablename array for some queries. This means you need to find the record based on some parameter and return something from the found record.
Do note that the record property is sometimes an array and sometimes an object (for table SurveyInfo) in your example so I'll assume you need to take this into account.
You can make a small function to extract data and handle both objects and arrays:
function extract(record, prop) {
if (Array.isArray(record)) {
return _.pluck(record, prop);
} else {
return record[prop];
}
}
Usage example:
I wanted all of the values for 'Code' in the 'QaQCPoints' table.
I'd also rather search for the 'Code' values in the table based on something like the '#text' key value, instead of just using it's position in the object.
To achieve this you first find a record using _.find, and then extract Code values from it using the method above:
var table = JSONData.surveyGDB.table.tablename;
// find an item that has `#text` property equal to `QaQcPoints`
var item = _.find(table, function(r) {
return r['#text'] === 'QaQcPoints';
});
// extract codes from the found item's record property
var code = extract(item.record, 'Code');
// output ["tp", "tb", "to", "bl", "bf"]
Running sample:
var JSONData = {
"surveyGDB": {
"filename": "..\\Topo\\SurveyGeoDatabase.gdb",
"table": {
"tablename": [{
"#text": "SurveyInfo",
"record": {
"OBJECTID": "1",
"SiteID": "CBW05583-345970",
"Watershed": "John Day",
"VisitType": "Initial visit",
"SurveyInstrument": "Total Station",
"ImportDate": "2015-07-22T09:08:42",
"StreamName": "Duncan Creek",
"InstrumentModel": "TopCon Magnet v2.5.1",
"FieldSeason": "2015"
}
}, {
"#text": "QaQcPoints",
"record": [{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tp",
"Count": "357"
}, {
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "tb",
"Count": "92"
}, {
"OBJECTID": "3",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "to",
"Count": "8"
}, {
"OBJECTID": "4",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bl",
"Count": "279"
}, {
"OBJECTID": "5",
"TIMESTAMP": "2015-07-22T09:18:43",
"Code": "bf",
"Count": "18"
}]
}, {
"#text": "QaQcPolygons",
"record": [{
"OBJECTID": "1",
"TIMESTAMP": "2015-07-22T09:43:08",
"SurveyExtentCount": "",
"WaterExtentCount": "",
"ChannelUnitsCount": "",
"ChannelUnitsUnique": ""
}, {
"OBJECTID": "2",
"TIMESTAMP": "2015-07-22T13:35:15",
"SurveyExtentCount": "1",
"WaterExtentCount": "1",
"ChannelUnitsCount": "21",
"ChannelUnitsUnique": "21"
}]
}]
}
}
}
function extract(record, prop) {
if (Array.isArray(record)) {
return _.pluck(record, prop);
} else {
return record[prop];
}
}
var table = JSONData.surveyGDB.table.tablename;
var item = _.find(table, function(r) {
return r['#text'] === 'QaQcPoints';
});
console.dir(item);
var code = extract(item.record, 'Code');
console.log(code);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
You have a two stage problem. Stage one is figuring out which table is QaQcPoints. If that's always JSONData.surveyGDB.table.tablename[1], you're good.
The next stage is getting your data out. You can use native array manipulation most of the time (unless you're on really old browsers). So:
var table = JSONData.surveyGDB.table.tablename[1].record;
var codeArray = table.map(function(val) { return val.Code; });
Will do the trick.

Creating Complex JSON Object using JavaScript Code

I am bit new to JSON world. And I have to use JavaScript to create following type of JSON structure. Not sure how to achieve this. Tried with following code, but unable to add second element("12101") as well as people to JSON Structure is where I am struggling.
var chat = {};
chat = {"101":{}};
chat["101"].people= {};
chat["101"].people = {"L0b12leL-Ar9GYKoAAAC":{}};
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"vikram#qech.com"};
chat["101"].room= {};
JSON structure to achieve
{
"101": {
"people": {
"L0b12leL-Ar9GYKoAAAC": {
"name": "vikram#qtech.com",
"inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
"countrycode": "in",
"device": "desktop",
"roomname": "R1"
},
"qKCglYWI1hRhZUZCAAAD": {
"name": "Ishim",
"inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"roomname": "Ra"
}
},
"room": {
"f787f316-6424-491b-b779-cfc396f0f8a1": {
"name": "R1",
"id": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owner": "L0b12leL-Ar9GYKoAAAC",
"people": [
"L0b12leL-Ar9GYKoAAAC"
],
"status": "available"
},
"2e52905d-951c-4990-b9b7-2f3fc0602922": {
"name": "Ra",
"id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owner": "qKCglYWI1hRhZUZCAAAD",
"people": [
"qKCglYWI1hRhZUZCAAAD"
],
"status": "available"
}
}
},
"12101": {
"people": {
"K-Ar9GYKoAAAC": {
"name": "Rahul.com",
"inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
"countrycode": "in",
"device": "desktop",
"roomname": "R1"
},
"I1hRhZUZCAAAD": {
"name": "Vipul",
"inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"roomname": "Ra"
}
},
"room": {
"b779-cfc396f0f8a1": {
"name": "Rahul-R1",
"id": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owner": "L0b12leL-Ar9GYKoAAAC",
"people": [
"L0b12leL-Ar9GYKoAAAC"
],
"status": "available"
},
"b9b7-2f3fc0602922": {
"name": "Vipul-Room1",
"id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owner": "qKCglYWI1hRhZUZCAAAD",
"people": [
"qKCglYWI1hRhZUZCAAAD"
],
"status": "available"
}
}
}
}
This is invalid because the property name contains dashes.
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"vikram#qech.com"};
To access it correctly, put it in quotes
chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"vikram#qech.com"};
Use bracket notation as a property accessor like this:
chat["12101"].people = {};
chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"vikram#qech.com"};
With it, it’s just a routine piece of work. It probably didn’t work right away since dot notation property access requires a valid identifier name. With bracket notation, you can use any string like "L0b12leL-Ar9GYKoAAAC".
Also note that in JSON, anything works as a property name too, as long as it is put in quotes. {"L0b12leL-Ar9GYKoAC":true} is as valid as {"💖":true}.

how to access nested objects with mustache js templating engine

I've this json return
{
"timeline": [{
"id": "2",
"self": {
"uid": "2",
"username": "ptamzz"
},
"file": {
"fid": "43",
"file_name": "First Name"
},
"connection": {
"fid": "4",
"username": "tom"
},
"action": "viewed your document",
"time": "2012-01-16 12:23:03",
"tags": ["Engineering", "Computer Science", "Java", "Java Library"]
}, {
"id": "1",
"self": {
"uid": "2",
"username": "ptamzz"
},
"file": {
"fid": "41",
"file_name": "Write Up"
},
"connection": {
"fid": "4",
"username": "tom"
},
"action": "favorited your document",
"time": "2012-01-16 12:22:04",
"tags": ["Design"]
}]
}
According to the tutorial at http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/ (Sample 6: Nested Object section), you can access dot notation to access the nested objects.
From the above json, I want to retrieve the data like self.username, file.file_name etc etc.
Now, I've my template as
{{#timeline}}
<li>
{{self.username}}
</li>
{{/timeline}}
But self.username doesn't work.
How do I retrieve these nested values?
I don't think it's the right way to do but since I couldn't find any answers here, I figured out something myself. At least this works.
{{#timeline}}
<li>
{{#self}}{{username}}{{/self}}
</li>
{{/timeline}}
Dot notation does not work on version 0.4x and below. It worked on "0.7.2".

Categories

Resources