ExtJS data model unknown amount of fields - javascript

I have a data model that attempts to map all the incoming data, however I have to leave the data generic so i can add any number of meta data tags to my project. How can I either map these data fields to the Model or access these items in the array when applying grid filters.
{
"Link": "link.com",
"Title": "project",
"Description": "descript",
"State": "TN",
"Metadata": [
{
"Name": "County",
"Value": "32"
},
{
"Name": "Info",
"Value": "info"
},
{
"Name": "State",
"Value": "TN"
}
],
"XMin": "-1",
"XMax": "-1",
"YMin": "1",
"YMax": "1"
}

I think this is what you are looking for https://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.association.HasMany
There is also nice explanation about filtering on that page

Related

JSON weird format access data

This is a JSON snip that is created in WooCommerce by a plugin that adds some metadata. I cannot change the formatting of this JSON because it is generated by a plugin. The problem is that the keys and the values are added in a weird way. I am iterating through the line_items and statically referencing this data which I don't want to do, I would like to know if there is a smart way to reference for example:
"key": "_cpo_product_id",
"value": "3572",
if this was formatted correctly it would be: "_cpo_product_id": "3572" and not have "value" as a key, and it would be accessed by: foo.line_items[i]._cpo_product_id
but with this configuration I am a bit lost, I am sure there is an easy way to find the value for a specific key. I am doing this on Google app scripts, but a solution in JavaScript should suffice.
JSON snip:
"line_items": [
{
"id": 749,
"name": "Dune",
"product_id": 3572,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "149.54",
"subtotal_tax": "31.40",
"total": "149.54",
"total_tax": "31.40",
"taxes": [
{
"id": 24,
"total": "31.403148",
"subtotal": "31.403148"
}
],
"meta_data": [
{
"id": 11919,
"key": "_cpo_product_id",
"value": "3572",
"display_key": "_cpo_product_id",
"display_value": "3572"
},
{
"id": 11920,
"key": "_add-to-cart",
"value": "3572",
"display_key": "_add-to-cart",
"display_value": "3572"
},

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.

Working With Dynamic Multidimensional key-value pairs in JSON

Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator

Query with join between documents

I would like to create a view in CouchDb which contains some fields from multiple linked documents.
My documents are something like this:
/*Products:*/
{
"_id": "Products:ABC",
"doctype": "Products",
"productCode": "ABC",
"description": "The best product you ever seen",
"category_id": "Categories:1",
"brand_id": "Brands:52"
},
{
"_id": "Products:DEF",
"doctype": "Products",
"productCode": "DEF",
"description": "DEFinitely a good product",
"category_id": "Categories:2",
"brand_id": "Brands:53"
},
/*Categories*/
{
"_id": "Categories:1",
"categoryID": "1",
"description": "Awesome products"
},
{
"_id": "Categories:2",
"categoryID": "2",
"description": "Wonderful supplies"
},
/*Brands*/
{
"_id": "Brands:52",
"brandID": "52",
"description": "Best Items"
},
{
"_id": "Brands:53",
"brandID": "53",
"description": "Great Gadgets"
},
I would like to have a result like this:
/*View results: */
{
"id": "Products:ABC",
"key": "Products:ABC",
"value": {
"productCode": "ABC",
"description": "The best product you ever seen",
"category": {
"categoryID": "1",
"description": "Awesome products"
},
"brand": {
"brandID": "52",
"description": "Best Items"
}
}
},
{
"id": "Products:DEF",
"key": "Products:DEF",
"value": {
"productCode": "DEF",
"description": "DEFinitely a good product",
"category": {
"categoryID": "2",
"description": "Wonderful supplies"
},
"brand": {
"brandID": "53",
"description": "Great Gadgets"
}
}
},
The goal is to have a result that is a join between the three documents. Is it possibile?
As you can imagine I come from the SQL world, so maybe I am designing the database terribly wrong, so any advice on how to change the documents structure is welcome!
Thanks in advance!
Francesco
There are two ways to do this:
Use the query() API and linked documents (search the page for "linked documents")
Use the relational-pouch plugin
The advantage of the relational-pouch plugin is that, under the hood, it is faster than linked documents because it doesn't rely on building up a map/reduce index. The advantage of linked documents is that it is the more traditional way of solving this problem in CouchDB, and it doesn't rely on an extra plugin. Choose whichever one you like. :)
Edit: re-reading your question, I see you want to join 3 different document types together. Currently that is not possible with linked documents (you can only "join" two types), whereas it is possible with relational-pouch. So I guess that makes the decision easy. :)

Backbone deep model setting atttibutes

I am trying to use [backbone deep model] (https://github.com/powmedia/backbone-deep-model) for the Person model which have nested attributes. The example code in github shows to set nested attributes like names
model.set({
'user.name.first': 'Lana',
'user.name.last': 'Kang'
});
but how to set model attributes otherSpies.name[0]:'Lana' ?
JSON format of my person model shown below.
{
"birthdate": "2005-10-26T00:00:00.000+0530",
"gender": "M",
"attributes": [
{
"value": "saagar.gugwad#gmail.com",
"attributeType": "8d6d7f78-9b9e-409a-96dc-ea8300e54175"
},
{
"value": "single",
"attributeType": "6b550dd7-ce73-4f14-af2d-35d1a37e7377"
},
{
"value": "7829730769",
"attributeType": "d1266776-7431-4fa4-9724-215c21418efb"
},
{
"value": "0",
"attributeType": "892089d1-f187-404b-89c3-96606194a05c"
},
{
"value": "AAAAAACAGwEtAAHMpTgHAAAAAElFTkSuQmCC\n",
"attributeType": "d5ac7b1d-a563-4661-9d9d-0ad6b8e346e8"
}
],
"addresses": [
{
"address1":"bla",
"address2":"bla2",
"street" :"walstreet",
"pincode" :"222FB"
}
],
"names": [
{
"familyName": "Dbh",
"givenName": "Saagar"
}
],
"age": 8
}
I want to set attributes using my personModel. How can I accomplish that ?

Categories

Resources