Getting out values from an array using angular.foreach in $scope - arrays

I have a dynamically changing array based on another code and I'm trying to retrieve specific data from the same.
Here is a sample of one dynamically generated array under $scope.filtereditem:
[{
"active": true,
"createdAt": "2015-10-05T20:19:58.264Z",
"desc": "With arugula, smoked almonds & chipotle vinaigrette",
"flavors": [{
"active": true,
"name": "Chocolate",
"price": 8
}, {
"active": false,
"name": "Strawberry",
"price": 8
}, {
"active": false,
"name": "Hazelnut",
"price": 8
}, {
"active": false,
"name": "Mint",
"price": 8
}],
"img": "https://signsrestaurant.ca/wp-content/uploads/2015/09/Watermelon-Quinoa-Jimaca-Salad.jpg",
"name": "Watermelon Quinoa Jicama Salad (<span class=\"vegan\">VE</span>, <span class=\"gfree\">GF</span>, <span class=\"dfree\">DF</span>)",
"objectId": "x1zpkWmvmP",
"price": 14,
"qty": 1,
"sides": [{
"active": false,
"name": "Soup"
}, {
"active": false,
"name": "Salad"
}, {
"active": false,
"name": "Fries"
}],
"sizes": [{
"active": false,
"name": "Small",
"price": 5
}, {
"active": true,
"name": "Medium",
"price": 10
}, {
"active": false,
"name": "Large",
"price": 15
}],
"type": "Soup",
"updatedAt": "2015-10-21T18:09:37.499Z"
}, {
"active": true,
"createdAt": "2015-10-05T20:35:01.363Z",
"desc": "Buffalo mozzarella, tomato, marinated artichoke hearts, black olives, pesto & balsamic drizzle",
"flavors": [{
"active": false,
"name": "Vanilla",
"price": 8
}, {
"active": false,
"name": "Almond",
"price": 8
}, {
"active": true,
"name": "Hazelnut",
"price": 8
}, {
"active": false,
"name": "Caramel",
"price": 8
}],
"img": "https://signsrestaurant.ca/wp-content/uploads/2015/09/Mediterranean-Salad.jpg",
"name": "Mediterranean Salad (<span class=\"veg\">V</span>, <span class=\"gfree\">GF</span>)",
"objectId": "nI5VSpdBUn",
"price": 15,
"qty": 2,
"sides": [{
"active": false,
"name": "Soup"
}, {
"active": false,
"name": "Salad"
}, {
"active": false,
"name": "Fries"
}],
"sizes": [{
"active": false,
"name": "Small",
"price": 0
}, {
"active": true,
"name": "Medium",
"price": 5
}, {
"active": false,
"name": "Large",
"price": 10
}],
"type": "Salad",
"updatedAt": "2015-10-21T18:09:33.422Z"
}]
That is just a sample and the array changes dynamically based on another code. What I wish to achieve is to retrieve certain data in the form of a scope element, let's name it as $scope.filteredmenu
This is where I'm stuck at. Here is what I have so far for this:
$scope.filteredmenu = function() {
var order = " ";
var side = " ";
angular.forEach($scope.filtereditem, function(item) {
var flavor = " ";
var size = " ";
order += item.name + "Qty: " + item.qty + " , ";
side += "Side: " + item.type + " , ";
angular.forEach(item.flavors, function(option) {
if (option && option.active) {
flavor += "Flavor: " + option.name + " , ";
}
});
angular.forEach(item.sizes, function(option) {
if (option && option.active) {
size += "Size: " + option.name + " , ";
}
});
menuorder += order + side + size + flavor;
});
return menuorder;
};
Basically, I need the output in this format:
For each item,
'item.name' Qty: 'item.qty', Side: 'item.type', Flavor (whichever is active): option.name (in item.flavors), Size (whichever is active): option.name (in item.sizes)
Eventually, I'm trying to send the result $scope.filteredmenu via an email API. I'm not sure what I'm doing wrong. Any help with this code would be much appreciated.

There were some syntax errors:
var output = function() {
var order = " ";
var side = " ";
//Not defined
var menuorder = '';
angular.forEach($scope.filtereditem, function(item) {
var flavor = " ";
var size = " ";
order += item.name + "Qty: " + item.qty + " , ";
//plus sign was missing
side += "Side: " + item.type + " , ";
angular.forEach(item.flavors, function(option) {
if (option && option.active) {
flavor += "Flavor: " + option.name + " , ";
}
});
angular.forEach(item.sizes, function(option) {
if (option && option.active) {
size += "Size: " + option.name + " , ";
}
});
menuorder += order + side + size + flavor;
});
return menuorder;
}
$scope.filteredmenu = output();
here is the working JSFiddler https://jsfiddle.net/hefc5ewe/

Related

Get path to a given node in Nested JSON array

I want to get the path to a given node, example if I provide key=8, then the result should be
**"ABC Company/Europe/hhhh" ** ``` Note -Depth of the array is unknown and the key is always unique,
I'm using spring boot as my backend framework.
[
{
"key": 1,
"label": "ABC Company",
"nodes": [
{
"key": 2,
"label": "Asia Pacific",
"nodes": [
{
"key": 3,
"label": "ttt",
"nodes": [],
"isLeaf": false
},
{
"key": 4,
"label": "thhhh",
"nodes": [],
"isLeaf": false
},
{
"key": 5,
"label": "hhhh",
"nodes": [
{
"key": 10,
"label": "test1",
"nodes": [],
"isLeaf": false
},
{
"key": 11,
"label": "test2",
"nodes": [],
"isLeaf": false
},
{
"key": 12,
"label": "test3",
"nodes": [],
"isLeaf": false
}
],
"isLeaf": false
}
],
"isLeaf": false
},
{
"key": 6,
"label": "Europe",
"nodes": [
{
"key": 7,
"label": "fff",
"nodes": [],
"isLeaf": false
},
{
"key": 8,
"label": "hhhh",
"nodes": [],
"isLeaf": false
},
{
"key": 9,
"label": "mmmm",
"nodes": [],
"isLeaf": false
}
],
"isLeaf": false
}
],
"isLeaf": false
}
]
I'm expecting to pass key value example if I pass key=8 then the output should be ABC Company/Europe/hhhh
I have tried these but they return the incorrect path
public String findNode(JsonNode jN, int id, String pR) throws JsonMappingException {
System.out.println("JN " + jN);
System.out.println("id " + id);
for (JsonNode item: jN) {
System.out.println("key " + item.get("key"));
pR = item.get("label").textValue();
System.out.println("pr " + pR);
if (item.get("key").intValue() == id) {
System.out.println("found key in findnode");
// return pR + "/" + item.get("label").textValue();
return item.get("label").textValue();
}
if (item.has("nodes") && item.get("nodes").hasNonNull(0)) {
JsonNode jN2 = item.get("nodes");
System.out.println("JN 2 " + jN2);
for (JsonNode item2: jN2) {
String recursiveResult = findNode(jN2, id, pR);
if (recursiveResult != "" | recursiveResult != null) return pR + "/" + recursiveResult;
}
}
}
return null;
}

Jest expect.any() not working as expected

So when testing one of my reducers in a Preact(not much different to React while testing with JEST) based project, I got bumped into this issue:
Following output comes up when running jest test -
● should setup
expect(received).toEqual(expected)
Expected value to equal:
{"ID": Any<String>, "active": true, "data": Any<Array>}
Received:
{"ID": "BysnEuMlm", "active": true, "data": [{"ID": "Hy7wMAz1lm", "code": "dat.fle", "label": "CRES/datum14.cdata", "name": "File", "status": "READY", "value": {"format": "cdata", "name": "datum14.cdata", "path": "CRES"}}, {"ID": "rkB7RMkeX", "code": "prp.kcv", "label": "3 folds", "name": "k-Fold Cross-Validation", "status": "READY", "value": "3"}, {"ID": "ByCmRfygQ", "code": "ats", "label": undefined, "name": " Best First + Cfs Subset Eval", "status": "READY", "value": {"evaluator": {"name": "CfsSubsetEval"}, "search": {"name": "BestFirst", "options": ["-D", "1", "-N", "5"]}, "use": true}}, {"ID": "HkmVAM1l7", "code": "lrn", "label": undefined, "name": "Naive Bayes", "status": "READY", "value": {"label": "Naive Bayes", "name": "bayes.NaiveBayes", "use": true}}], "output": {"format": "pipeline", "name": "jestReact.cpipe", "path": "/home/rupav/opensource/candis/CRES"}}
Difference:
- Expected
+ Received
Object {
- "ID": Any<String>,
+ "ID": "BysnEuMlm",
"active": true,
- "data": Any<Array>,
+ "data": Array [
+ Object {
+ "ID": "Hy7wMAz1lm",
+ "code": "dat.fle",
+ "label": "CRES/datum14.cdata",
+ "name": "File",
+ "status": "READY",
+ "value": Object {
+ "format": "cdata",
+ "name": "datum14.cdata",
+ "path": "CRES",
+ },
+ },
+ Object {
+ "ID": "rkB7RMkeX",
+ "code": "prp.kcv",
+ "label": "3 folds",
+ "name": "k-Fold Cross-Validation",
+ "status": "READY",
+ "value": "3",
+ },
+ Object {
+ "ID": "ByCmRfygQ",
+ "code": "ats",
+ "label": undefined,
+ "name": " Best First + Cfs Subset Eval",
+ "status": "READY",
+ "value": Object {
+ "evaluator": Object {
+ "name": "CfsSubsetEval",
+ },
+ "search": Object {
+ "name": "BestFirst",
+ "options": Array [
+ "-D",
+ "1",
+ "-N",
+ "5",
+ ],
+ },
+ "use": true,
+ },
+ },
+ Object {
+ "ID": "HkmVAM1l7",
+ "code": "lrn",
+ "label": undefined,
+ "name": "Naive Bayes",
+ "status": "READY",
+ "value": Object {
+ "label": "Naive Bayes",
+ "name": "bayes.NaiveBayes",
+ "use": true,
+ },
+ },
+ ],
+ "output": Object {
+ "format": "pipeline",
+ "name": "jestReact.cpipe",
+ "path": "/home/rupav/opensource/candis/CRES",
+ },
}
Following is the test case:
test('should setup ', () => {
const state = documentProcessor(
undefined,
{
type: ActionType.Asynchronous.READ_SUCCESS,
payload: dokuments.active
})
// expect(state.active.ID).toEqual(expect.any(String)) - Test case passes iff I run this test with this command only.
expect(state.active).toEqual({
data: expect.any(Array),
active: true,
ID: expect.any(String),
})
})
Since state gets changed while calling that reducer, I needed to use expect.any function, but as per the output, although types are same, test is not getting passed.
Rather in expected its showing up Any<String>.
expect.toEqual checks for equality of state.active in your case. To achieve what you want, you have to make multiple expect statements:
expect(state.active.active).toEqual(true)
expect(state.active.data).toEqual(expect.any(Array))
expect(state.active.ID).toEqual(expect.any(String))
You can use toMatchObject:
expect(state.active).toMatchObject({
active: true,
data: expect.any(Array),
ID: expect.any(String)
});
See more examples in official documentation: https://jestjs.io/docs/en/expect#tomatchobjectobject

How can I ensure alphabetical order with json schema of json objects in json arrays?

I would like to ensure that json objects within a json array are ordered correctly by a specific property with a json schema.
Is that possible? And if so, how can I create such a json schema?
Schema:
{
"type": "object",
"properties": {
"cities": {
"type": "array",
"items": {
"type": "object",
"properties": {
"shortName": {
"type": "string"
},
"name": {
"type": "string"
},
"showInMap": {
"type": "boolean"
},
"active": {
"type": "boolean"
}
},
"??ORDERBY??": "shortName",
"??ORDER??": "ASC",
"required": [
"shortName"
]
}
}
}
}
I would like to filter out json files which are not correctly ordered.
Example: (invalid)
{
"cities": [
{
"shortName": "NY",
"name": "New York",
"showInMap": true,
"active": true
},
{
"shortName": "LD",
"name": "London",
"showInMap": true,
"active": false
},
{
"shortName": "MO",
"name": "Moscow",
"showInMap": false,
"active": false
}
]
}
And accept json files which are ordered correctly.
Example: (valid)
{
"cities": [
{
"shortName": "LD",
"name": "London",
"showInMap": true,
"active": false
},
{
"shortName": "MO",
"name": "Moscow",
"showInMap": false,
"active": false
},{
"shortName": "NY",
"name": "New York",
"showInMap": true,
"active": true
}
]
}
EDIT: This answer makes no use of json schema.
Here is a minimal solution working on your sample data. It is not safe for production, as it is missing all sorts of checks for undefined, but I think you can enhance it at will.
function isSorted(array, sortKey) {
return array.reduce((ordered, item, index) => {
return index > array.length - 2 ? ordered : ordered && item[sortKey] < array[index + 1][sortKey];
}, true);
}
const incorrectCase = [{
"shortName": "NY",
"name": "New York",
"showInMap": true,
"active": true
},
{
"shortName": "LD",
"name": "London",
"showInMap": true,
"active": false
},
{
"shortName": "MO",
"name": "Moscow",
"showInMap": false,
"active": false
}
]
const correctCase = [{
"shortName": "LD",
"name": "London",
"showInMap": true,
"active": false
},
{
"shortName": "MO",
"name": "Moscow",
"showInMap": false,
"active": false
}, {
"shortName": "NY",
"name": "New York",
"showInMap": true,
"active": true
}
];
console.log('incorrect case: ', isSorted(incorrectCase, "shortName"));
console.log('correct case: ', isSorted(correctCase, "shortName"));

AngularJS/Angular 2: Restructure the json after getting 'http' response

Current:
[{
"name": "a1",
"category": "C1",
"amount": 10
},
{
"name": "a3",
"category": "C1",
"amount": 30
},
{
"name": "a2",
"category": "C1",
"amount": 20
},
{
"name": "a1",
"category": "C2",
"amount": 100
},
{
"name": "a6",
"category": "C2",
"amount": 600
},
{
"name": "a2",
"category": "C2",
"amount": 200
},
{
"name": "a5",
"category": "C2",
"amount": 500
},
{
"name": "a1",
"category": "C3",
"amount": 1000
},
{
"name": "a3",
"category": "C3",
"amount": 3000
},
{
"name": "a5",
"category": "C3",
"amount": 5000
}
]
convert to:
[
{
"name": "a1",
"C1": 10,
"C2": 100,
"C3": 1000
},
{
"name": "a2",
"C1": 20,
"C2": 200,
"C3": -
},
{
"name": "a3",
"C1": 30,
"C2": -,
"C3": 3000
},
{
"name": "a5",
"C1": -,
"C2": 500,
"C3": 5000
},
{
"name": "a6",
"C1": -,
"C2": 600,
"C3": -
}
]
If you want only the properties that have been passed in (e.g. if there is no C2 for a1, then the mapped a1 will not have a C2 property):
var response = {} //set this equal to your original response, rather than an empty object
var list = {}
var mappedResponse = [];
let mapResponse = () => {
response.forEach(item => {
current = list[item.name] || {};
current.name = item.name;
current[item.category] = item.amount;
list[item.name] = current;
});
Object.keys(list).forEach(key => {
mappedResponse.push(list[key]);
});
return mappedResponse;
}
mapResponse();
If you wanted to explicitly declare something like null for those empty fields, rather than having them be undefined, you could change the forEach to look like this:
response.forEach(item => {
current = list[item.name] || {};
current.name = item.name;
current['C1'] = item.category === 'C1' ? item.amount : current['C1'] || null;
current['C2'] = item.category === 'C2' ? item.amount : current['C2'] || null;
current['C3'] = item.category === 'C3' ? item.amount : current['C3'] || null;
list[item.name] = current;
});
Here is my version!
Please not the output JSON you wanted contains the below line.
"C3": -
I checked whether the JSON is valid or not on JSONLint.com and I got the below error.
Error: Parse error on line 14: ... "C2": 200, "C3": - }, { "name":
----------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
This will make the JSON invalid. So what is suggest is to leave out this property! Please let me know if that is fine?
//starting JSON
var json = [{
"name": "a1",
"category": "C1",
"amount": 10
},
{
"name": "a3",
"category": "C1",
"amount": 30
},
{
"name": "a2",
"category": "C1",
"amount": 20
},
{
"name": "a1",
"category": "C2",
"amount": 100
},
{
"name": "a6",
"category": "C2",
"amount": 600
},
{
"name": "a2",
"category": "C2",
"amount": 200
},
{
"name": "a5",
"category": "C2",
"amount": 500
},
{
"name": "a1",
"category": "C3",
"amount": 1000
},
{
"name": "a3",
"category": "C3",
"amount": 3000
},
{
"name": "a5",
"category": "C3",
"amount": 5000
}
]
var out=[];
var final = [];
//code used to filter out the unique names ["a1", "a2", etc]
for (let a of json){
if(out.indexOf(a.name) === -1){
out.push(a.name);
}
}
//loop through the unique names!
for (let a of out){
var obj = {};
//filter the object for a particular name
for(let j of json.filter(function(x){return x.name===a})){
//merge the objects `category` and `amount` as a object
Object.assign(obj, {[j.category]: j.amount});
}
//finally push it to the final list that is `final`
var temp = {name: a};
Object.assign(temp, obj);
final.push(temp);
}
//console.log the output
console.log(final);

Hive on JSON File

I need help in parsing the JSON file using HIVE. This file has nested arrays, when i tried to parse the file or query using the HiVE UDF i can drill down just to one level. Then next level arrays were coming up Null in my result. I have given the example below. File has couple of sections (array ), but below given one is most complex one. I tried to use get_json_object to parse, i was able to get data just one level, it didn't pull the nested arrays at all. It would be helpful if someone guide me in parsing the nested json arrays
"section": {
"moodCode": "xxx",
"classCode": "xxx",
"templateId": {
"root": "2.xx.840"
},
"code": {
"codeSystemName": "LOINC",
},
"title": "problems",
"text": {
"mediaType": "text/x-hl7-text+xml",
"list": [{
"caption": "Recorded",
"item": {
"ID": "pr101",
"content": [{
"ID": "pr101-desc",
"text": "Salm"
},
"003.1"],
"text": " "
},
"text": " "
},
{
"caption": "Reported",
"item": "None Reported",
"text": " "
}],
"text": " "
},
"entry": {
"typeCode": "DRIV",
"act": {
"moodCode": "EVN",
"classCode": "ACT",
"templateId": [{
"root": "2.16.840.1.0.1.27"
},
{
"root": "1.3.6.1.4..1"
},
{
"root": "1.3.6.1.4.4.5.2"
}],
"id": {
"root": "068fd4d4-dfa2-48190768f"
},
"code": {
"nullFlavor": "NA"
},
"statusCode": {
"code": "completed"
},
"effectiveTime": {
"low": {
"value": "20140428144743+0100"
},
"high": {
"value": "20140428144743+0100"
},
"text": " "
},
"entryRelationship": {
"typeCode": "SUBJ",
"observation": {
"moodCode": "EVN",
"classCode": "OBS",
"templateId": [{
"root": "2.16.840.1.20.1.28"
},
{
"root": "1.3.6.1.4.1.5.3.1.4.5"
}],
"id": {
"root": "fa34b4da4dbb-b090-01bd4d6ef62b"
},
"code": {
"codeSystemName": "SNOMED CT",
"code": "282009",
"displayName": "diagnosis",
"codeSystem": "2.16.840.1.6.96"
},
"text": {
"reference": {
"value": "#pr101"
},
"text": " "
},
"statusCode": {
"code": "completed"
},
"effectiveTime": {
"low": {
"value": "20140428144743+0100"
},
"high": {
"nullFlavor": "UNK"
},
"text": " "
},
"value": {
"codeSystemName": "ICD-9",
"xsi:type": "CD",
"code": "003.1",
"displayName": "Sla sia",
"codeSystem": "2.16.840.1.103",
"originalText": {
"reference": {
"value": "#pr101-desc"
},
"text": " "
},
"text": " "
},
"entryRelationship": {
"typeCode": "REFR",
"observation": {
"moodCode": "EVN",
"classCode": "OBS",
"templateId": [{
"root": "2.16.840..1.50"
},
{
"root": "2.16.8410.20.1.57"
},
{
"root": "1.3.6.13.1.4.1.1"
}],
"code": {
"codeSystemName": "LOINC",
"code": "33999-4",
"displayName": "Status",
"codeSystem": "2.16.840.1.113883.6.1"
},
"statusCode": {
"code": "completed"
},
"value": {
"codeSystemName": " CT",
"xsi:type": "CE",
"code": "55563",
"displayName": "active",
"codeSystem": "2.16.8406.96"
},
"text": " "
},
"text": " "
},
"text": " "
},
"text": " "
},
"text": " "
},
"text": " "
},
"text": " "
},
"text": " "
},
When i used get_json_object below mentioned data came up null.
"title": "problems",
"text": {
"mediaType": "text/x-hl7-text+xml",
"list": [{
"caption": "Recorded",
"item": {
"ID": "pr101",
"content": [{
"ID": "pr101-desc",
"text": "Salm"
},
"003.1"],
updated-you have to format your JSON file in such a way that each record should be in just one line, like
'{"section":{"moodCode":"xxx","classCode":"xxx","templateId":{"root":"2.xx.840"},"code":{"codeSystemName":"LOINC"},"title":"problems","text":{"mediaType":"text/x-hl7-text+xml","list":[{"caption":"Recorded","item":{"ID":"pr101","content":[{"ID":"pr101-desc","text":"Salm"},"003.1"],"text":" "},"text":" "},{"caption":"Reported","item":"None Reported","text":" "}],"text":" "},"entry":{"typeCode":"DRIV","act":{"moodCode":"EVN","classCode":"ACT","templateId":[{"root":"2.16.840.1.0.1.27"},{"root":"1.3.6.1.4..1"},{"root":"1.3.6.1.4.4.5.2"}],"id":{"root":"068fd4d4-dfa2-48190768f"},"code":{"nullFlavor":"NA"},"statusCode":{"code":"completed"},"effectiveTime":{"low":{"value":"20140428144743+0100"},"high":{"value":"20140428144743+0100"},"text":""},"entryRelationship":{"typeCode":"SUBJ","observation":{"moodCode":"EVN","classCode":"OBS","templateId":[{"root":"2.16.840.1.20.1.28"},{"root":"1.3.6.1.4.1.5.3.1.4.5"}],"id":{"root":"fa34b4da4dbb-b090-01bd4d6ef62b"},"code":{"codeSystemName":"SNOMEDCT","code":"282009","displayName":"diagnosis","codeSystem":"2.16.840.1.6.96"},"text":"","statusCode":{"code":"completed"},"effectiveTime":{"low":{"value":"20140428144743+0100"},"high":{"nullFlavor":"UNK"},"text":""},"value":{"codeSystemName":"ICD-9","xsi: type":"CD","code":"003.1","displayName":"Slasia","codeSystem":"2.16.840.1.103","originalText":{"reference":{"value":"#pr101-desc"},"text":""},"text":""},"entryRelationship":{"typeCode":"REFR","observation":{"moodCode":"EVN","classCode":"OBS","templateId":[{"root":"2.16.840..1.50"},{"root":"2.16.8410.20.1.57"},{"root":"1.3.6.13.1.4.1.1"}],"code":{"codeSystemName":"LOINC","code":"33999-4","displayName":"Status","codeSystem":"2.16.840.1.113883.6.1"},"statusCode":{"code":"completed"},"value":{"codeSystemName":"CT","xsi: type":"CE","code":"55563","displayName":"active","codeSystem":"2.16.8406.96"},"text":""},"text":""}},"text":""},"text":""},"text":""}},"text":""}'
Now create a table treating the entire string as one column
'drop table json_test;
create external table json_test(value string)
LOCATION 'path'; '
you can lateral view json_tuple to get the fields you need now.
'set hive.cli.print.header=true;
SELECT c.moodCode,c.classCode,d.root,c.title,e.mediaType FROM json_test a LATERAL VIEW json_tuple(a.value, 'section') b AS section LATERAL VIEW json_tuple(b.section,'moodCode','classCode','templateId','title','text')c
AS moodCode,classCode,templateId,title,text LATERAL VIEW json_tuple(c.templateId,'root')d
AS root LATERAL VIEW json_tuple(c.text,'mediaType')e AS mediaType;'
result
'c.moodcode|c.classcode|d.root |c.title |e.mediatype
xxx | xxx |2.xx.840 |problems|text/x-hl7-text+xml'

Resources