javascript json iteration to get key and value - javascript

I am trying to iterate the json below, I have got this as an output of an astify of sql parser. Now i want to validate the column type with a DB schema that i have.
{
"with": null,
"type": "select",
"options": null,
"distinct": null,
"columns": "*",
"from": [
{
"db": null,
"table": "TABLE_1",
"as": null
}
],
"where": {
"type": "binary_expr",
"operator": "AND",
"left": {
"type": "binary_expr",
"operator": "AND",
"left": {
"type": "binary_expr",
"operator": "=",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_1"
},
"right": {
"type": "string",
"value": "NORM"
}
},
"right": {
"type": "binary_expr",
"operator": "IN",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_2"
},
"right": {
"type": "expr_list",
"value": [
{
"type": "string",
"value": "11"
},
{
"type": "string",
"value": "12"
},
{
"type": "string",
"value": "13"
},
{
"type": "string",
"value": "14"
},
{
"type": "string",
"value": "15"
},
{
"type": "string",
"value": "16"
},
{
"type": "string",
"value": "17"
},
{
"type": "string",
"value": "18"
},
{
"type": "string",
"value": "42"
},
{
"type": "string",
"value": "43"
},
{
"type": "string",
"value": "44"
},
{
"type": "string",
"value": "45"
},
{
"type": "string",
"value": "101"
},
{
"type": "string",
"value": "102"
},
{
"type": "string",
"value": "103"
},
{
"type": "string",
"value": "104"
},
{
"type": "string",
"value": "128"
},
{
"type": "string",
"value": "129"
},
{
"type": "string",
"value": "130"
},
{
"type": "string",
"value": "131"
},
{
"type": "string",
"value": "159"
}
]
}
}
},
"right": {
"type": "binary_expr",
"operator": "OR",
"left": {
"type": "binary_expr",
"operator": "IS NOT",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_3"
},
"right": {
"type": "null",
"value": null
}
},
"right": {
"type": "binary_expr",
"operator": "=",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_4"
},
"right": {
"type": "number",
"value": 1
}
},
"parentheses": true
}
},
"groupby": null,
"having": null,
"orderby": null,
"limit": null
}
Can you please help me get an output like which will help me identify the column and its type whether its string or not. Basically i need to validate the query whether its mapped against the correct data type while using a var condition.
Output like:
map = <key,value>
<Column_1, String>
<Column_2, String>
<Column_3, INT>
etc.

#Suzy, please check below code for your reference:
var arr = {
"with": null,
"type": "select",
"options": null,
"distinct": null,
"columns": "*",
"from": [
{
"db": null,
"table": "TABLE_1",
"as": null
}
],
"where": {
"type": "binary_expr",
"operator": "AND",
"left": {
"type": "binary_expr",
"operator": "AND",
"left": {
"type": "binary_expr",
"operator": "=",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_1"
},
"right": {
"type": "string",
"value": "NORM"
}
},
"right": {
"type": "binary_expr",
"operator": "IN",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_2"
},
"right": {
"type": "expr_list",
"value": [
{
"type": "string",
"value": "11"
},
{
"type": "string",
"value": "12"
},
{
"type": "string",
"value": "13"
},
{
"type": "string",
"value": "14"
},
{
"type": "string",
"value": "15"
},
{
"type": "string",
"value": "16"
},
{
"type": "string",
"value": "17"
},
{
"type": "string",
"value": "18"
},
{
"type": "string",
"value": "42"
},
{
"type": "string",
"value": "43"
},
{
"type": "string",
"value": "44"
},
{
"type": "string",
"value": "45"
},
{
"type": "string",
"value": "101"
},
{
"type": "string",
"value": "102"
},
{
"type": "string",
"value": "103"
},
{
"type": "string",
"value": "104"
},
{
"type": "string",
"value": "128"
},
{
"type": "string",
"value": "129"
},
{
"type": "string",
"value": "130"
},
{
"type": "string",
"value": "131"
},
{
"type": "string",
"value": "159"
}
]
}
}
},
"right": {
"type": "binary_expr",
"operator": "OR",
"left": {
"type": "binary_expr",
"operator": "IS NOT",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_3"
},
"right": {
"type": "null",
"value": null
}
},
"right": {
"type": "binary_expr",
"operator": "=",
"left": {
"type": "column_ref",
"table": null,
"column": "COLUMN_4"
},
"right": {
"type": "number",
"value": 1
}
},
"parentheses": true
}
},
"groupby": null,
"having": null,
"orderby": null,
"limit": null
};
function findProp(obj, key, out) {
var i,
proto = Object.prototype,
ts = proto.toString,
hasOwn = proto.hasOwnProperty.bind(obj);
if ('[object Array]' !== ts.call(out)) out = [];
for (i in obj) {
if (hasOwn(i)) {
if (i === key) {
out.push(obj[i]);
} else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
findProp(obj[i], key, out);
}
}
}
return out;
}
console.log(findProp(arr, "column"));

Parse the JSON into an object using JSON.parse(), then iterate through them while checking if the value is JSON or not.
Check if the value is JSON by using catch on JSON.parse()
To get the object keys for iteration, Use var keys = Object.keys();

Related

Is it possible to get specific value from deeply nested JSON string?

I am trying to get specific value from deeply nested stringified JSON.
Below is the example
const arr = [
{
"type": "exception-handler",
"action": "try-catch",
"extra": {
"id": "aefwwefefwARG#.[t.2"
},
"try": [
{
"type": "unit",
"action": "create",
"request": [
{
"type": "operator",
"action": "request",
"extra": {
"id": "%m6nwefewfqAuo!#"
},
"id": "58282ac47ccc45b79c6bc",
"method": {
"type": "miscellaneous",
"action": "protocol-method",
"extra": {
"id": "H+JewwefeTgHv"
},
"method": "post"
},
"end-point": {
"type": "protocol-end-point",
"action": "url",
"extra": {
"id": "=wefwefqe"
},
"end-point": {
"type": "primitive",
"action": "string",
"extra": {
"id": "wefwefewfewd!"
},
"value": "http://localhost:8081/plan/entrance"
}
},
"header": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "[wvsdvsdvsdvY"
},
"values": [
{
"type": "parameter",
"action": "create",
"extra": {
"id": "sdfwefwef"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "sdfvwvwv_-|z*"
},
"value": "Content-Type"
},
"value": {
"type": "miscellaneous",
"action": "protocol-content-type",
"content-type": "application/json"
},
"description": {
"type": "primitive",
"action": "string",
"extra": {
"id": "4xW$1)uu^o5Qyd*:_%b-"
},
"value": "Content-Type"
},
"datatype": {
"type": "miscellaneous",
"action": "parameter-type",
"extra": {
"id": "0q;~b_SF4bUu|y`I~5#W"
},
"parameter-type": "string"
},
"required": {
"type": "primitive",
"action": "boolean",
"extra": {
"id": "pddddvwvewerr"
},
"value": true
}
}
]
},
"body": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "wecwcecweqweq"
},
"values": []
}
}
],
"response": [
{
"type": "operator",
"action": "response",
"extra": {
"id": "u^ewfvwKlbu"
},
"id": "d2a26b2943c12fc9c493cb152773c1ad",
"context": [
{
"type": "response-context",
"action": "create",
"extra": {
"id": "/wfefwf]JbM"
},
"status_code": {
"type": "primitive",
"action": "integer",
"extra": {
"id": "bYhweqwdqwVZs:~"
},
"value": 200
},
"header": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "$0{7z~p%Yp.{`SMtV!o#"
},
"values": [
{
"type": "parameter",
"action": "create",
"extra": {
"id": "efwefwB"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "#9.Rwefvwvfs"
},
"value": "Content-Type"
},
"value": {
"type": "miscellaneous",
"action": "protocol-content-type",
"content-type": "application/json"
},
"description": {
"type": "primitive",
"action": "strwffwe",
"extra": {
"id": "I=jUZ6Xc-u}UfqHqe8T6"
},
"value": "Content-Type"
},
"datatype": {
"type": "miscellaneous",
"action": "parameter-type",
"extra": {
"id": "B*(qy~(zjjjI-,u*aN-."
},
"parameter-type": "string"
},
"required": {
"type": "primitive",
"action": "boolean",
"extra": {
"id": "!_4.P~5A#DR(.#j#tee_"
},
"value": true
}
}
]
},
"body": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "2xlF!I#063F+ag4%AGGn"
},
"values": [
{
"type": "parameter",
"action": "create",
"extra": {
"id": "QNc=;UPk5m`g?d+p$F;)"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "fX7,hQW_SvG-HI_Kbvc,"
},
"value": "result"
},
"value": {
"type": "variable",
"action": "get",
"extra": {
"id": "_41Rlcb++on)q=sb,i$e"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "31AhsBljlkYm=9aLy+Wt"
},
"value": "qqq1"
}
},
"description": {
"type": "primitive",
"action": "string",
"extra": {
"id": "Si$=Ebxj{Yyt2yI;s#:e"
},
"value": "result"
},
"datatype": {
"type": "miscellaneous",
"action": "parameter-type",
"extra": {
"id": "L3Z?PB8k6)D]5##_U*63"
},
"parameter-type": "string"
},
"required": {
"type": "primitive",
"action": "boolean",
"extra": {
"id": "=3QlBlyN%72a#E{!4ovC"
},
"value": false
}
}
]
}
}
]
}
],
"statements": [
{
"type": "helper",
"action": "code-section",
"extra": {
"id": ")$x]%MY;vXFM66t$[#3g"
},
"statements": [
{
"type": "document",
"action": "comment-note",
"extra": {
"id": "8prbh]Hq?^s2BV=`J4|$"
},
"comment": {
"type": "primitive",
"action": "string",
"value": "code 1"
}
},
{
"type": "variable",
"action": "create",
"extra": {
"id": "QubE)kG{r7H9xR-}CHF7"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "h=rET1COg7/YoxR{OfYz"
},
"value": "qqq2"
}
},
{
"type": "variable",
"action": "set",
"extra": {
"id": "p[gSm|F$#CU3M_F!Tl!o"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "Y9)#ccnXbtpN}[zq!U!a"
},
"value": "qqq2"
},
"value": {
"type": "pair",
"action": "create",
"extra": {
"id": "b=/HL|O--7^=~{c4]SYk"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "2,aMj#kiv$aG]2Fg(X+F"
},
"value": "qqq"
},
"value": {
"type": "pair",
"action": "create",
"extra": {
"id": "_]kqE^cuy#mK!s5~KufR"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "u9v[T7T4t]oRB)KMKAo7"
},
"value": "qqq"
},
"value": {
"type": "primitive",
"action": "string",
"extra": {
"id": "/,V=$)=-Ex*1KAQpKim7"
},
"value": "1234"
}
}
}
}
]
},
{
"type": "helper",
"action": "code-section",
"extra": {
"id": "Nwefwvwwe|T;2"
},
"statements": [
{
"type": "document",
"action": "comment-note",
"extra": {
"id": "!hba3~wcwe+!AjcF"
},
"comment": {
"type": "primitive",
"action": "string",
"value": "code 2"
}
},
{
"type": "variable",
"action": "create",
"extra": {
"id": "`.zqkDw?Qd$BD#;U`pb7"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "awefwvevK~0Y"
},
"value": "qqq1"
}
},
{
"type": "variable",
"action": "set",
"extra": {
"id": "S,wVwvvefdwefFx/"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": ":QwevdsdvdWex"
},
"value": "qqq1"
},
"value": {
"type": "custom-util",
"action": "create",
"extra": {
"id": "xLwedwvwev|K"
},
"arguments": [
{
"type": "pair",
"action": "create",
"extra": {
"id": "ig-vsdvsdO0O80D!"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "AJOawef`hZ|d,"
},
"value": "arg1"
},
"value": {
"type": "primitive",
"action": "null",
"extra": {
"id": "8MraKndfsdf;$MF4Cb"
}
}
},
{
"type": "pair",
"action": "create",
"extra": {
"id": "`eeGi4|7oGaRT7UB;AvP"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "vewdqwd4X"
},
"value": "arg2"
},
"value": {
"type": "primitive",
"action": "null",
"extra": {
"id": "Xcswefsddv,"
}
}
}
],
"payload": [],
"return-value": {
"type": "primitive",
"action": "string",
"extra": {
"id": "eodx(7Oz7)7Gw;.dF4kt"
},
"value": "retData"
},
"property": {
"type": "property",
"action": "custom-util",
"extra": [],
"id": {
"type": "primitive",
"action": "string",
"extra": [],
"value": "3e1589wewefewfq2332cc2a83"
},
"name": {
"type": "primitive",
"action": "string",
"extra": [],
"value": "test1"
},
"description": {
"type": "primitive",
"action": "string",
"extra": [],
"value": ""
},
"created-date": {
"type": "primitive",
"action": "string",
"extra": [],
"value": ""
},
"updated-date": {
"type": "primitive",
"action": "string",
"extra": [],
"value": ""
}
}
}
}
]
}
]
}
],
"catchers": [
{
"type": "exception-handler",
"action": "exception-catcher",
"extra": {
"id": "6ZCfwefwfewfO)f}UF!"
},
"id": "064673gerg081c4e1",
"exceptions": [
{
"type": "miscellaneous",
"action": "exception-type",
"extra": {
"id": "IQRLF7Shgd46:T!UXA~V"
},
"exception-type": "RuntimeException"
}
],
"statements": []
}
]
}
];
This is deeply nested array with object and it could be nested deeper. And I want to get string ids inside extra object.
"extra": {
"id": "aefwwefefwARG#.[t.2"
},
And make them as a set of array like below.
const ids = ["aefwwefefwARG#.[t.2", "%m6nwefewfqAuo!#", "H+JewwefeTgHv", ...]
I used JSON.stringify method to flatten the array. However, I forgot when I use the method, the array is converted to a string. Therefore I am not able to get the specific object with key name extra.
Is there way I can get the value of extra from stringified array?
You probably don't need to JSON.stringify.
If your json structure is in an object json.
You can try something like:
function findKeyValuesInJson(json, needle_key, nested_needle) {
let found_values = [];
let objectsToCheck = [json];
while(objectsToCheck.length > 0) {
let obj = objectsToCheck.pop();
let keysToCheck = Object.keys(obj);
while(keysToCheck.length > 0) {
let key = keysToCheck.pop();
if (key === needle_key) {
found_values.push(obj[key])
if(nested_needle && typeof obj[key] === 'object' && obj[key] !== null) {
objectsToCheck.push(obj[key]);
}
} else if (typeof obj[key] === 'object' && obj[key] !== null) {
objectsToCheck.push(obj[key]);
}
}
}
return found_values;
}
function findExtraInJson(json) {
return findKeyValuesInJson(json, 'extra');
}
const extraProps = findExtraInJson(json);
It basically iterates through the entire object and collects the
values of key extra in an array.
By default, we're not checking the key extra again for the key extra. You can enable that by passing true as the third argument to findKeyValuesInJson or you can put the if statement with objectsToCheck(obj[key]) outside the else-if statement so that all keys will go through with this check.
After getting the property values in an array, you can filter/map it and get what you need like this:
extraProps
.filter(extra => extra.id !== undefined)
.map(extra => extra.id);
Just another approach recursively visiting an array passed as input and returning an array of values of all the .extra.id property values found in its nested objects.
As a side note, please forget what you think to know about json. That's a formal syntax to serialize javascript objects. You actually have a javascript object definition there and that's all we need here. JSON.stringify would be needed to serialize the object but it's not our approach here.
This is the main logics:
//visits the arr array recursively looking for objects having .extra.id
//that, if found, will be pushed in the accumulator
function grabExtraIds(arr, accumulator = []) {
//for each item in the array
arr.forEach(nestedObject => {
//pushes the .extra.id value of this nestedObject if existent
const extraId = nestedObject ? .extra ? .id;
if (extraId !== undefined)
accumulator.push(extraId);
//for each property of the current nestedObject
Object.getOwnPropertyNames(nestedObject)
.forEach(propertyName => {
const property = nestedObject[propertyName];
//if the property value is of type array
if (Array.isArray(property))
//recursively call the grabExtraIds with this object
grabExtraIds(property, accumulator);
});
});
}
This is the found ids:
[
"aefwwefefwARG#.[t.2",
"%m6nwefewfqAuo!#",
"u^ewfvwKlbu",
"/wfefwf]JbM",
")$x]%MY;vXFM66t$[#3g",
"8prbh]Hq?^s2BV=`J4|$",
"QubE)kG{r7H9xR-}CHF7",
"p[gSm|F$#CU3M_F!Tl!o",
"Nwefwvwwe|T;2",
"!hba3~wcwe+!AjcF",
"`.zqkDw?Qd$BD#;U`pb7",
"S,wVwvvefdwefFx/",
"6ZCfwefwfewfO)f}UF!",
"IQRLF7Shgd46:T!UXA~V"
]
And this is the live demo:
const arr = [{
"type": "exception-handler",
"action": "try-catch",
"extra": {
"id": "aefwwefefwARG#.[t.2"
},
"try": [{
"type": "unit",
"action": "create",
"request": [{
"type": "operator",
"action": "request",
"extra": {
"id": "%m6nwefewfqAuo!#"
},
"id": "58282ac47ccc45b79c6bc",
"method": {
"type": "miscellaneous",
"action": "protocol-method",
"extra": {
"id": "H+JewwefeTgHv"
},
"method": "post"
},
"end-point": {
"type": "protocol-end-point",
"action": "url",
"extra": {
"id": "=wefwefqe"
},
"end-point": {
"type": "primitive",
"action": "string",
"extra": {
"id": "wefwefewfewd!"
},
"value": "http://localhost:8081/plan/entrance"
}
},
"header": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "[wvsdvsdvsdvY"
},
"values": [{
"type": "parameter",
"action": "create",
"extra": {
"id": "sdfwefwef"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "sdfvwvwv_-|z*"
},
"value": "Content-Type"
},
"value": {
"type": "miscellaneous",
"action": "protocol-content-type",
"content-type": "application/json"
},
"description": {
"type": "primitive",
"action": "string",
"extra": {
"id": "4xW$1)uu^o5Qyd*:_%b-"
},
"value": "Content-Type"
},
"datatype": {
"type": "miscellaneous",
"action": "parameter-type",
"extra": {
"id": "0q;~b_SF4bUu|y`I~5#W"
},
"parameter-type": "string"
},
"required": {
"type": "primitive",
"action": "boolean",
"extra": {
"id": "pddddvwvewerr"
},
"value": true
}
}]
},
"body": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "wecwcecweqweq"
},
"values": []
}
}],
"response": [{
"type": "operator",
"action": "response",
"extra": {
"id": "u^ewfvwKlbu"
},
"id": "d2a26b2943c12fc9c493cb152773c1ad",
"context": [{
"type": "response-context",
"action": "create",
"extra": {
"id": "/wfefwf]JbM"
},
"status_code": {
"type": "primitive",
"action": "integer",
"extra": {
"id": "bYhweqwdqwVZs:~"
},
"value": 200
},
"header": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "$0{7z~p%Yp.{`SMtV!o#"
},
"values": [{
"type": "parameter",
"action": "create",
"extra": {
"id": "efwefwB"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "#9.Rwefvwvfs"
},
"value": "Content-Type"
},
"value": {
"type": "miscellaneous",
"action": "protocol-content-type",
"content-type": "application/json"
},
"description": {
"type": "primitive",
"action": "strwffwe",
"extra": {
"id": "I=jUZ6Xc-u}UfqHqe8T6"
},
"value": "Content-Type"
},
"datatype": {
"type": "miscellaneous",
"action": "parameter-type",
"extra": {
"id": "B*(qy~(zjjjI-,u*aN-."
},
"parameter-type": "string"
},
"required": {
"type": "primitive",
"action": "boolean",
"extra": {
"id": "!_4.P~5A#DR(.#j#tee_"
},
"value": true
}
}]
},
"body": {
"type": "hashmap",
"action": "create",
"extra": {
"id": "2xlF!I#063F+ag4%AGGn"
},
"values": [{
"type": "parameter",
"action": "create",
"extra": {
"id": "QNc=;UPk5m`g?d+p$F;)"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "fX7,hQW_SvG-HI_Kbvc,"
},
"value": "result"
},
"value": {
"type": "variable",
"action": "get",
"extra": {
"id": "_41Rlcb++on)q=sb,i$e"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "31AhsBljlkYm=9aLy+Wt"
},
"value": "qqq1"
}
},
"description": {
"type": "primitive",
"action": "string",
"extra": {
"id": "Si$=Ebxj{Yyt2yI;s#:e"
},
"value": "result"
},
"datatype": {
"type": "miscellaneous",
"action": "parameter-type",
"extra": {
"id": "L3Z?PB8k6)D]5##_U*63"
},
"parameter-type": "string"
},
"required": {
"type": "primitive",
"action": "boolean",
"extra": {
"id": "=3QlBlyN%72a#E{!4ovC"
},
"value": false
}
}]
}
}]
}],
"statements": [{
"type": "helper",
"action": "code-section",
"extra": {
"id": ")$x]%MY;vXFM66t$[#3g"
},
"statements": [{
"type": "document",
"action": "comment-note",
"extra": {
"id": "8prbh]Hq?^s2BV=`J4|$"
},
"comment": {
"type": "primitive",
"action": "string",
"value": "code 1"
}
},
{
"type": "variable",
"action": "create",
"extra": {
"id": "QubE)kG{r7H9xR-}CHF7"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "h=rET1COg7/YoxR{OfYz"
},
"value": "qqq2"
}
},
{
"type": "variable",
"action": "set",
"extra": {
"id": "p[gSm|F$#CU3M_F!Tl!o"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "Y9)#ccnXbtpN}[zq!U!a"
},
"value": "qqq2"
},
"value": {
"type": "pair",
"action": "create",
"extra": {
"id": "b=/HL|O--7^=~{c4]SYk"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "2,aMj#kiv$aG]2Fg(X+F"
},
"value": "qqq"
},
"value": {
"type": "pair",
"action": "create",
"extra": {
"id": "_]kqE^cuy#mK!s5~KufR"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "u9v[T7T4t]oRB)KMKAo7"
},
"value": "qqq"
},
"value": {
"type": "primitive",
"action": "string",
"extra": {
"id": "/,V=$)=-Ex*1KAQpKim7"
},
"value": "1234"
}
}
}
}
]
},
{
"type": "helper",
"action": "code-section",
"extra": {
"id": "Nwefwvwwe|T;2"
},
"statements": [{
"type": "document",
"action": "comment-note",
"extra": {
"id": "!hba3~wcwe+!AjcF"
},
"comment": {
"type": "primitive",
"action": "string",
"value": "code 2"
}
},
{
"type": "variable",
"action": "create",
"extra": {
"id": "`.zqkDw?Qd$BD#;U`pb7"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": "awefwvevK~0Y"
},
"value": "qqq1"
}
},
{
"type": "variable",
"action": "set",
"extra": {
"id": "S,wVwvvefdwefFx/"
},
"name": {
"type": "primitive",
"action": "string",
"extra": {
"id": ":QwevdsdvdWex"
},
"value": "qqq1"
},
"value": {
"type": "custom-util",
"action": "create",
"extra": {
"id": "xLwedwvwev|K"
},
"arguments": [{
"type": "pair",
"action": "create",
"extra": {
"id": "ig-vsdvsdO0O80D!"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "AJOawef`hZ|d,"
},
"value": "arg1"
},
"value": {
"type": "primitive",
"action": "null",
"extra": {
"id": "8MraKndfsdf;$MF4Cb"
}
}
},
{
"type": "pair",
"action": "create",
"extra": {
"id": "`eeGi4|7oGaRT7UB;AvP"
},
"key": {
"type": "primitive",
"action": "string",
"extra": {
"id": "vewdqwd4X"
},
"value": "arg2"
},
"value": {
"type": "primitive",
"action": "null",
"extra": {
"id": "Xcswefsddv,"
}
}
}
],
"payload": [],
"return-value": {
"type": "primitive",
"action": "string",
"extra": {
"id": "eodx(7Oz7)7Gw;.dF4kt"
},
"value": "retData"
},
"property": {
"type": "property",
"action": "custom-util",
"extra": [],
"id": {
"type": "primitive",
"action": "string",
"extra": [],
"value": "3e1589wewefewfq2332cc2a83"
},
"name": {
"type": "primitive",
"action": "string",
"extra": [],
"value": "test1"
},
"description": {
"type": "primitive",
"action": "string",
"extra": [],
"value": ""
},
"created-date": {
"type": "primitive",
"action": "string",
"extra": [],
"value": ""
},
"updated-date": {
"type": "primitive",
"action": "string",
"extra": [],
"value": ""
}
}
}
}
]
}
]
}],
"catchers": [{
"type": "exception-handler",
"action": "exception-catcher",
"extra": {
"id": "6ZCfwefwfewfO)f}UF!"
},
"id": "064673gerg081c4e1",
"exceptions": [{
"type": "miscellaneous",
"action": "exception-type",
"extra": {
"id": "IQRLF7Shgd46:T!UXA~V"
},
"exception-type": "RuntimeException"
}],
"statements": []
}]
}];
//visits the arr array recursively looking for objects having .extra.id that will be pushed in the accumulator
function grabExtraIds(arr, accumulator = []){
//for each item in the array
arr.forEach(nestedObject => {
//pushes the .extra.id value of this nestedObject if existent
const extraId = nestedObject?.extra?.id;
if(extraId !== undefined)
accumulator.push( extraId );
//for each property of the current nestedObject
Object.getOwnPropertyNames(nestedObject)
.forEach( propertyName =>{
const property = nestedObject[propertyName];
//if the property value is of type array
if (Array.isArray(property))
//recursively call the grabExtraIds with this object
grabExtraIds(property, accumulator);
});
});
}
const result = [];
grabExtraIds(arr, result);
console.log(result);
You can do this using a recursive function, let's call it getAllPropertyValues().
We loop over each key in the input object obj, if the value at that key is an object (or array) we call getAllPropertyValues on the value, if not we'll add the value to the result array if it matches the desired property.
You could use a Set() if you wished to get only unique ids rather than each and every one.
We'll match only the desired extra objects by passing in a parent value and testing against each object's parent.
const arr = [ { "type": "exception-handler", "action": "try-catch", "extra": { "id": "aefwwefefwARG#.[t.2" }, "try": [ { "type": "unit", "action": "create", "request": [ { "type": "operator", "action": "request", "extra": { "id": "%m6nwefewfqAuo!#" }, "id": "58282ac47ccc45b79c6bc", "method": { "type": "miscellaneous", "action": "protocol-method", "extra": { "id": "H+JewwefeTgHv" }, "method": "post" }, "end-point": { "type": "protocol-end-point", "action": "url", "extra": { "id": "=wefwefqe" }, "end-point": { "type": "primitive", "action": "string", "extra": { "id": "wefwefewfewd!" }, "value": "http://localhost:8081/plan/entrance" } }, "header": { "type": "hashmap", "action": "create", "extra": { "id": "[wvsdvsdvsdvY" }, "values": [ { "type": "parameter", "action": "create", "extra": { "id": "sdfwefwef" }, "key": { "type": "primitive", "action": "string", "extra": { "id": "sdfvwvwv_-|z*" }, "value": "Content-Type" }, "value": { "type": "miscellaneous", "action": "protocol-content-type", "content-type": "application/json" }, "description": { "type": "primitive", "action": "string", "extra": { "id": "4xW$1)uu^o5Qyd*:_%b-" }, "value": "Content-Type" }, "datatype": { "type": "miscellaneous", "action": "parameter-type", "extra": { "id": "0q;~b_SF4bUu|y`I~5#W" }, "parameter-type": "string" }, "required": { "type": "primitive", "action": "boolean", "extra": { "id": "pddddvwvewerr" }, "value": true } } ] }, "body": { "type": "hashmap", "action": "create", "extra": { "id": "wecwcecweqweq" }, "values": [] } } ], "response": [ { "type": "operator", "action": "response", "extra": { "id": "u^ewfvwKlbu" }, "id": "d2a26b2943c12fc9c493cb152773c1ad", "context": [ { "type": "response-context", "action": "create", "extra": { "id": "/wfefwf]JbM" }, "status_code": { "type": "primitive", "action": "integer", "extra": { "id": "bYhweqwdqwVZs:~" }, "value": 200 }, "header": { "type": "hashmap", "action": "create", "extra": { "id": "$0{7z~p%Yp.{`SMtV!o#" }, "values": [ { "type": "parameter", "action": "create", "extra": { "id": "efwefwB" }, "key": { "type": "primitive", "action": "string", "extra": { "id": "#9.Rwefvwvfs" }, "value": "Content-Type" }, "value": { "type": "miscellaneous", "action": "protocol-content-type", "content-type": "application/json" }, "description": { "type": "primitive", "action": "strwffwe", "extra": { "id": "I=jUZ6Xc-u}UfqHqe8T6" }, "value": "Content-Type" }, "datatype": { "type": "miscellaneous", "action": "parameter-type", "extra": { "id": "B*(qy~(zjjjI-,u*aN-." }, "parameter-type": "string" }, "required": { "type": "primitive", "action": "boolean", "extra": { "id": "!_4.P~5A#DR(.#j#tee_" }, "value": true } } ] }, "body": { "type": "hashmap", "action": "create", "extra": { "id": "2xlF!I#063F+ag4%AGGn" }, "values": [ { "type": "parameter", "action": "create", "extra": { "id": "QNc=;UPk5m`g?d+p$F;)" }, "key": { "type": "primitive", "action": "string", "extra": { "id": "fX7,hQW_SvG-HI_Kbvc," }, "value": "result" }, "value": { "type": "variable", "action": "get", "extra": { "id": "_41Rlcb++on)q=sb,i$e" }, "name": { "type": "primitive", "action": "string", "extra": { "id": "31AhsBljlkYm=9aLy+Wt" }, "value": "qqq1" } }, "description": { "type": "primitive", "action": "string", "extra": { "id": "Si$=Ebxj{Yyt2yI;s#:e" }, "value": "result" }, "datatype": { "type": "miscellaneous", "action": "parameter-type", "extra": { "id": "L3Z?PB8k6)D]5##_U*63" }, "parameter-type": "string" }, "required": { "type": "primitive", "action": "boolean", "extra": { "id": "=3QlBlyN%72a#E{!4ovC" }, "value": false } } ] } } ] } ], "statements": [ { "type": "helper", "action": "code-section", "extra": { "id": ")$x]%MY;vXFM66t$[#3g" }, "statements": [ { "type": "document", "action": "comment-note", "extra": { "id": "8prbh]Hq?^s2BV=`J4|$" }, "comment": { "type": "primitive", "action": "string", "value": "code 1" } }, { "type": "variable", "action": "create", "extra": { "id": "QubE)kG{r7H9xR-}CHF7" }, "name": { "type": "primitive", "action": "string", "extra": { "id": "h=rET1COg7/YoxR{OfYz" }, "value": "qqq2" } }, { "type": "variable", "action": "set", "extra": { "id": "p[gSm|F$#CU3M_F!Tl!o" }, "name": { "type": "primitive", "action": "string", "extra": { "id": "Y9)#ccnXbtpN}[zq!U!a" }, "value": "qqq2" }, "value": { "type": "pair", "action": "create", "extra": { "id": "b=/HL|O--7^=~{c4]SYk" }, "key": { "type": "primitive", "action": "string", "extra": { "id": "2,aMj#kiv$aG]2Fg(X+F" }, "value": "qqq" }, "value": { "type": "pair", "action": "create", "extra": { "id": "_]kqE^cuy#mK!s5~KufR" }, "key": { "type": "primitive", "action": "string", "extra": { "id": "u9v[T7T4t]oRB)KMKAo7" }, "value": "qqq" }, "value": { "type": "primitive", "action": "string", "extra": { "id": "/,V=$)=-Ex*1KAQpKim7" }, "value": "1234" } } } } ] }, { "type": "helper", "action": "code-section", "extra": { "id": "Nwefwvwwe|T;2" }, "statements": [ { "type": "document", "action": "comment-note", "extra": { "id": "!hba3~wcwe+!AjcF" }, "comment": { "type": "primitive", "action": "string", "value": "code 2" } }, { "type": "variable", "action": "create", "extra": { "id": "`.zqkDw?Qd$BD#;U`pb7" }, "name": { "type": "primitive", "action": "string", "extra": { "id": "awefwvevK~0Y" }, "value": "qqq1" } }, { "type": "variable", "action": "set", "extra": { "id": "S,wVwvvefdwefFx/" }, "name": { "type": "primitive", "action": "string", "extra": { "id": ":QwevdsdvdWex" }, "value": "qqq1" }, "value": { "type": "custom-util", "action": "create", "extra": { "id": "xLwedwvwev|K" }, "arguments": [ { "type": "pair", "action": "create", "extra": { "id": "ig-vsdvsdO0O80D!" }, "key": { "type": "primitive", "action": "string", "extra": { "id": "AJOawef`hZ|d," }, "value": "arg1" }, "value": { "type": "primitive", "action": "null", "extra": { "id": "8MraKndfsdf;$MF4Cb" } } }, { "type": "pair", "action": "create", "extra": { "id": "`eeGi4|7oGaRT7UB;AvP" }, "key": { "type": "primitive", "action": "string", "extra": { "id": "vewdqwd4X" }, "value": "arg2" }, "value": { "type": "primitive", "action": "null", "extra": { "id": "Xcswefsddv," } } } ], "payload": [], "return-value": { "type": "primitive", "action": "string", "extra": { "id": "eodx(7Oz7)7Gw;.dF4kt" }, "value": "retData" }, "property": { "type": "property", "action": "custom-util", "extra": [], "id": { "type": "primitive", "action": "string", "extra": [], "value": "3e1589wewefewfq2332cc2a83" }, "name": { "type": "primitive", "action": "string", "extra": [], "value": "test1" }, "description": { "type": "primitive", "action": "string", "extra": [], "value": "" }, "created-date": { "type": "primitive", "action": "string", "extra": [], "value": "" }, "updated-date": { "type": "primitive", "action": "string", "extra": [], "value": "" } } } } ] } ] } ], "catchers": [ { "type": "exception-handler", "action": "exception-catcher", "extra": { "id": "6ZCfwefwfewfO)f}UF!" }, "id": "064673gerg081c4e1", "exceptions": [ { "type": "miscellaneous", "action": "exception-type", "extra": { "id": "IQRLF7Shgd46:T!UXA~V" }, "exception-type": "RuntimeException" } ], "statements": [] } ] } ];
function getAllPropertyValues(obj, property, parent, parentKey = '') {
let values = [];
for(let k in obj) {
if (obj[k] && typeof(obj[k]) === 'object') {
values = [...values, ...getAllPropertyValues(obj[k], property, parent, k)]
} else if ((k === property) && (parent === parentKey)) {
values.push(obj[k])
}
}
return values;
}
console.log('Id array:', getAllPropertyValues(arr, 'id', 'extra'))
.as-console-wrapper { max-height: 100% !important; }

Change value or remove object from array of objects

I've an array of objects and I need to change the values or "decorate" array:
If value in some object is empty, remove whole object from the array.
If value is an object, take only label or name
My array:
[
{ "name": "certificate", "value": "", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Certificate", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "manufacturer", "value": "China Mint", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Manufacturer", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "countryOfOrigin", "value": "China", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Country of origin", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "grossWeight", "value": 30, "attributeDefinition": { "type": { "name": "number", "__typename": "NumberAttributeDefinitionType" }, "label": "Gross weight", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "yearsOfIssue", "value": [ "2017" ], "attributeDefinition": { "type": { "name": "set", "__typename": "SetAttributeDefinitionType" }, "label": "Year(s) of issue", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "fineWeightUnit", "value": { "key": "g", "label": "g" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Fine weight unit", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "packaging", "value": " ", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Packaging", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "preciousMetal", "value": { "key": "gold", "label": "Gold" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Precious metal", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
]
expected output:
[
{ "name": "manufacturer", "value": "China Mint", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Manufacturer", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "countryOfOrigin", "value": "China", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Country of origin", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "grossWeight", "value": 30, "attributeDefinition": { "type": { "name": "number", "__typename": "NumberAttributeDefinitionType" }, "label": "Gross weight", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "yearsOfIssue", "value": "2017", "attributeDefinition": { "type": { "name": "set", "__typename": "SetAttributeDefinitionType" }, "label": "Year(s) of issue", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "fineWeightUnit", "value": { "label": "g" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Fine weight unit", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "preciousMetal", "value": { "label": "Gold" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Precious metal", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
]
any idea how to handle it?
this way...
const data =
[
{ "name": "certificate", "value": "", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Certificate", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "manufacturer", "value": "China Mint", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Manufacturer", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "countryOfOrigin", "value": "China", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Country of origin", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "grossWeight", "value": 30, "attributeDefinition": { "type": { "name": "number", "__typename": "NumberAttributeDefinitionType" }, "label": "Gross weight", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "yearsOfIssue", "value": [ "2017" ], "attributeDefinition": { "type": { "name": "set", "__typename": "SetAttributeDefinitionType" }, "label": "Year(s) of issue", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "fineWeightUnit", "value": { "key": "g", "label": "g" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Fine weight unit", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "packaging", "value": " ", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Packaging", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "preciousMetal", "value": { "key": "gold", "label": "Gold" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Precious metal", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
]
data.reduceRight( (z,el,indx,arr) =>
{
if (Object.prototype.toString.call(el.value) === '[object Object]')
{
Object.keys(el.value).forEach( k=> { if (k!=='label' && k!=='name') delete el.value[k] } )
if (Object.keys(el.value).length === 0)
{
arr.splice(indx, 1)
}
}
else if ( el.value.length === 0 || ( typeof(el.value) === 'string' && /^\s*$/.test(el.value) ) )
{
arr.splice(indx, 1)
}
}
, null )
console.log( data )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
One of the approaches could be
let array = [
{ "name": "manufacturer", "value": "China Mint", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Manufacturer", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "countryOfOrigin", "value": "China", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Country of origin", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "grossWeight", "value": 30, "attributeDefinition": { "type": { "name": "number", "__typename": "NumberAttributeDefinitionType" }, "label": "Gross weight", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "yearsOfIssue", "value": "2017", "attributeDefinition": { "type": { "name": "set", "__typename": "SetAttributeDefinitionType" }, "label": "Year(s) of issue", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "fineWeightUnit", "value": { "label": "g" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Fine weight unit", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "preciousMetal", "value": { "label": "Gold" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Precious metal", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
]
let newArr = array.map((item) => {
if (!item.value) return
if (typeof item === "object" && Object.keys(item).length > 0) {
if (item["key"]) {
delete item["key"]
}
return item
} else return item
});
console.log(newArr)
My approach to handle this issue will be:
const arr = [{
"name": "certificate",
"value": "",
"attributeDefinition": {
"type": {
"name": "text",
"__typename": "TextAttributeDefinitionType"
},
"label": "Certificate",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
{
"name": "manufacturer",
"value": "China Mint",
"attributeDefinition": {
"type": {
"name": "text",
"__typename": "TextAttributeDefinitionType"
},
"label": "Manufacturer",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
{
"name": "countryOfOrigin",
"value": "China",
"attributeDefinition": {
"type": {
"name": "text",
"__typename": "TextAttributeDefinitionType"
},
"label": "Country of origin",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
{
"name": "grossWeight",
"value": 30,
"attributeDefinition": {
"type": {
"name": "number",
"__typename": "NumberAttributeDefinitionType"
},
"label": "Gross weight",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
{
"name": "yearsOfIssue",
"value": ["2017"],
"attributeDefinition": {
"type": {
"name": "set",
"__typename": "SetAttributeDefinitionType"
},
"label": "Year(s) of issue",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
{
"name": "fineWeightUnit",
"value": {
"key": "g",
"label": "g"
},
"attributeDefinition": {
"type": {
"name": "enum",
"__typename": "EnumAttributeDefinitionType"
},
"label": "Fine weight unit",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
{
"name": "packaging",
"value": " ",
"attributeDefinition": {
"type": {
"name": "text",
"__typename": "TextAttributeDefinitionType"
},
"label": "Packaging",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
{
"name": "preciousMetal",
"value": {
"key": "gold",
"label": "Gold"
},
"attributeDefinition": {
"type": {
"name": "enum",
"__typename": "EnumAttributeDefinitionType"
},
"label": "Precious metal",
"__typename": "AttributeDefinition"
},
"__typename": "RawProductAttribute"
},
];
arr.forEach((objects, index) => {
for (let object in objects) {
if (typeof objects[object] !== 'object') {
let value = objects[object].toString().trim();
if (!value.length) {
arr.splice(index, 1);
}
} else {
if (!objects[object].toString().trim().length) {
arr.splice(index, 1);
}
}
}
})
Here is a proposal, you can filter to remove empty values and make a map with a condition on type of the value property.
const data = [
{ "name": "certificate", "value": "", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Certificate", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "manufacturer", "value": "China Mint", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Manufacturer", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "countryOfOrigin", "value": "China", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Country of origin", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "grossWeight", "value": 30, "attributeDefinition": { "type": { "name": "number", "__typename": "NumberAttributeDefinitionType" }, "label": "Gross weight", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "yearsOfIssue", "value": [ "2017" ], "attributeDefinition": { "type": { "name": "set", "__typename": "SetAttributeDefinitionType" }, "label": "Year(s) of issue", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "fineWeightUnit", "value": { "key": "g", "label": "g" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Fine weight unit", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "packaging", "value": " ", "attributeDefinition": { "type": { "name": "text", "__typename": "TextAttributeDefinitionType" }, "label": "Packaging", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
{ "name": "preciousMetal", "value": { "key": "gold", "label": "Gold" }, "attributeDefinition": { "type": { "name": "enum", "__typename": "EnumAttributeDefinitionType" }, "label": "Precious metal", "__typename": "AttributeDefinition" }, "__typename": "RawProductAttribute" },
]
const arrNoEmptyValues = data.filter( element => element.value && element.value != " ")
const result = arrNoEmptyValues.map( element => {
if(typeof element.value === "object") {
return {
...element,
value:{ label: element.value.label || "", name: element.value.name || "" }
}
}
else {
return element
}
})
//there is a case you didn't forecast it's when there is no name nor label in value, i propose to return empty "" label and name in this case, so your object structure when value is an object is more consistent
console.log(result)

Unable to do POST using AJAX in SAP UI5 for non-odata restful service

I am trying to do POST request using AJAX and I am unable to post it. I am getting 401 Unauthorized error and getting error in request "email: ["The email has already been taken."]". Below is SAP UI5 controller function where i am doing ajax call and I have also shared API as well.Can someone please identify where the problem is?
SAP UI5 Controller:
var url = "http://url/api/url";
var data = {
"picture" : "test",
"member_cnic" : "weq",
"sign" : "test",
"ref_no" : "12345",
"person_no" : "12345",
"other_no" : "Othernumber",
"first_name" : "Muhammad",
"middle_name" : "adnan",
"last_name" : "Aadi",
"father_name" : "Muhammad",
"dob" : "1992-02-10",
"gender" : "Male",
"cnic" : "0986543456",
"passport_no" : "543456789",
"nationality" : "pakistani",
"religion" : "Lahore",
"phone_no" : "09876543234",
"email" : "test#gmail.com",
"is_active" : "0",
"academics[0][degree_examination]" : "xyz",
"academics[0][pass_month]" : "6",
"academics[0][pass_year]" : "2",
"academics[0][session]" : "A",
"academics[0][grade]" : "B+",
"academics[0][division]" : "1st",
"academics[0][organization]" : "UOL",
"academics[0][is_exemption]" : "0",
"academics[0][user_id]" : "2",
"addresses[0][address1]" : "UOL",
"addresses[0][address2]" : "UOL",
"addresses[0][address3]" : "UOL",
"addresses[0][address4]" : "UOL",
"addresses[0][postal_code]" : "76554",
"addresses[0][city]" : "Lahore",
"addresses[0][district]" : "Lahore",
"addresses[0][tehsil]" : "Bahria",
"addresses[0][province]" : "Punjab",
"addresses[0][country]" : "Pakistan",
"addresses[0][region]" : "Bahria Town",
"addresses[0][zone]" : "Lahore",
"addresses[0][phone1]" : "083290273",
"addresses[0][phone2]" : "343522242",
"addresses[0][ext_no]" : "884",
"addresses[0][fax]" : "345352626",
"addresses[0][type]" : "Teacher",
"addresses[0][mark_permanent_address_as_residential]" : "0",
"addresses[0][user_id]" : "1",
"experience[0][designation]" : "Manager",
"experience[0][organization]" : "UOL",
"experience[0][address]" : "Bahria",
"experience[0][city]" : "Lahore",
"experience[0][country]" : "Pakistan",
"experience[0][start_date]" : "2010-02-10",
"experience[0][end_date]" : "2010-02-10",
"experience[0][is_current]" : "0",
"experience[0][user_id]" : "12",
"trainings[0][principal_mrt_name]" : "hello",
"trainings[0][organization]" : "UOL",
"trainings[0][city]" : "UK",
"trainings[0][country]" : "UK",
"trainings[0][crn]" : "2323",
"trainings[0][start_date]" : "2010-02-10",
"trainings[0][end_date]" : "2010-02-10",
"trainings[0][address]" : "UOL",
"trainings[0][user_id]" : "12",
"mSettings[ref_no]" : "234",
"mSettings[designation]" : "Manager",
"mSettings[department]" : "cs",
"mSettings[organization]" : "uol",
"mSettings[publish_email1_in_directory]" : "0",
"mSettings[publish_email1_in_mailing_list]" : "0",
"mSettings[publish_email1_in_obituary]" : "0",
"mSettings[publish_email2_in_directory]" : "0",
"mSettings[publish_email2_in_mailing_list]" : "0",
"mSettings[publish_email2_in_obituary]" : "0",
"mSettings[publish_cell_in_directory]" : "0",
"mSettings[publish_cell_in_mailing_list]" : "0",
"mSettings[sms_facility]" : "0",
"mSettings[period_of_residence_in_pakistan]" : "12",
"mSettings[publish_communication_address_in_directory]" : "0",
"mSettings[communication_address]" : "Town Lahore",
}
$.ajax({
url: url,
type: 'POST',
mode: 'formdata',
data: data,
contentType: 'application/x-www-form-urlencoded',
success: function(data){
console.log("success"+data);
},
error: function(e){
console.log("error: "+e);
}
});
API
{
"info": {
"_postman_id": "9c7dbf23-21cb-4ec5-b7ee-b8794c8be930",
"name": "Member Registration Copy",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "API",
"item": [
{
"name": "http://url",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "picture",
"type": "text",
"value": "wqe"
},
{
"key": "member_cnic",
"type": "text",
"value": "123"
},
{
"key": "sign",
"type": "text",
"value": "iopdpsad"
},
{
"key": "ref_no",
"value": "12345",
"type": "text"
},
{
"key": "person_no",
"value": "12345",
"type": "text"
},
{
"key": "other_no",
"value": "Othernumber",
"type": "text"
},
{
"key": "first_name",
"value": "Muhammad",
"type": "text"
},
{
"key": "middle_name",
"value": "adnan",
"type": "text"
},
{
"key": "last_name",
"value": "Aadi",
"type": "text"
},
{
"key": "father_name",
"value": "Muhammad",
"type": "text"
},
{
"key": "dob",
"value": "1992-02-10",
"type": "text"
},
{
"key": "gender",
"value": "Male",
"type": "text"
},
{
"key": "cnic",
"value": "0986543456",
"type": "text"
},
{
"key": "passport_no",
"value": "543456789",
"type": "text"
},
{
"key": "nationality",
"value": "pakistani",
"type": "text"
},
{
"key": "religion",
"value": "Lahore",
"type": "text"
},
{
"key": "phone_no",
"value": "09876543234",
"type": "text"
},
{
"key": "email",
"value": "test#gmail.com",
"type": "text"
},
{
"key": "is_active",
"value": "0",
"type": "text"
},
{
"key": "academics[0][degree_examination]",
"value": "xyz",
"type": "text"
},
{
"key": "academics[0][pass_month]",
"value": "6",
"type": "text"
},
{
"key": "academics[0][pass_year]",
"value": "2",
"type": "text"
},
{
"key": "academics[0][session]",
"value": "A",
"type": "text"
},
{
"key": "academics[0][grade]",
"value": "B+",
"type": "text"
},
{
"key": "academics[0][division]",
"value": "1st",
"type": "text"
},
{
"key": "academics[0][organization]",
"value": "UOL",
"type": "text"
},
{
"key": "academics[0][is_exemption]",
"value": "0",
"type": "text"
},
{
"key": "academics[0][user_id]",
"value": "2",
"type": "text"
},
{
"key": "addresses[0][address1]",
"value": "UOL",
"type": "text"
},
{
"key": "addresses[0][address2]",
"value": "UOL",
"type": "text"
},
{
"key": "addresses[0][address3]",
"value": "UOL",
"type": "text"
},
{
"key": "addresses[0][address4]",
"value": "UOL",
"type": "text"
},
{
"key": "addresses[0][postal_code]",
"value": "76554",
"type": "text"
},
{
"key": "addresses[0][city]",
"value": "Lahore",
"type": "text"
},
{
"key": "addresses[0][district]",
"value": "Lahore",
"type": "text"
},
{
"key": "addresses[0][tehsil]",
"value": "Bahria",
"type": "text"
},
{
"key": "addresses[0][province]",
"value": "Punjab",
"type": "text"
},
{
"key": "addresses[0][country]",
"value": "Pakistan",
"type": "text"
},
{
"key": "addresses[0][region]",
"value": "Town",
"type": "text"
},
{
"key": "addresses[0][zone]",
"value": "Lahore",
"type": "text"
},
{
"key": "addresses[0][phone1]",
"value": "083290273",
"type": "text"
},
{
"key": "addresses[0][phone2]",
"value": "343522242",
"type": "text"
},
{
"key": "addresses[0][ext_no]",
"value": "884",
"type": "text"
},
{
"key": "addresses[0][fax]",
"value": "345352626",
"type": "text"
},
{
"key": "addresses[0][type]",
"value": "Teacher",
"type": "text"
},
{
"key": "addresses[0][mark_permanent_address_as_residential]",
"value": "0",
"type": "text"
},
{
"key": "addresses[0][user_id]",
"value": "1",
"type": "text"
},
{
"key": "experience[0][designation]",
"value": "Manager",
"type": "text"
},
{
"key": "experience[0][organization]",
"value": "UOL",
"type": "text"
},
{
"key": "experience[0][address]",
"value": "Bahria",
"type": "text"
},
{
"key": "experience[0][city]",
"value": "Lahore",
"type": "text"
},
{
"key": "experience[0][country]",
"value": "Pakistan",
"type": "text"
},
{
"key": "experience[0][start_date]",
"value": "2010-02-10",
"type": "text"
},
{
"key": "experience[0][end_date]",
"value": "2010-02-10",
"type": "text"
},
{
"key": "experience[0][is_current]",
"value": "0",
"type": "text"
},
{
"key": "experience[0][user_id]",
"value": "12",
"type": "text"
},
{
"key": "trainings[0][principal_mrt_name]",
"value": "hello",
"type": "text"
},
{
"key": "trainings[0][organization]",
"value": "UOL",
"type": "text"
},
{
"key": "trainings[0][city]",
"value": "UK",
"type": "text"
},
{
"key": "trainings[0][country]",
"value": "UK",
"type": "text"
},
{
"key": "trainings[0][crn]",
"value": "2323",
"type": "text"
},
{
"key": "trainings[0][start_date]",
"value": "2010-02-10",
"type": "text"
},
{
"key": "trainings[0][end_date]",
"value": "2010-02-10",
"type": "text"
},
{
"key": "trainings[0][address]",
"value": "UOL",
"type": "text"
},
{
"key": "trainings[0][user_id]",
"value": "12",
"type": "text"
},
{
"key": "mSettings[ref_no]",
"value": "234",
"type": "text"
},
{
"key": "mSettings[designation]",
"value": "Manager",
"type": "text"
},
{
"key": "mSettings[department]",
"value": "cs",
"type": "text"
},
{
"key": "mSettings[organization]",
"value": "uol",
"type": "text"
},
{
"key": "mSettings[publish_email1_in_directory]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[publish_email1_in_mailing_list]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[publish_email1_in_obituary]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[publish_email2_in_directory]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[publish_email2_in_mailing_list]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[publish_email2_in_obituary]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[publish_cell_in_directory]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[publish_cell_in_mailing_list]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[sms_facility]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[period_of_residence_in_pakistan]",
"value": "12",
"type": "text"
},
{
"key": "mSettings[publish_communication_address_in_directory]",
"value": "0",
"type": "text"
},
{
"key": "mSettings[communication_address]",
"value": "Town Lahore",
"type": "text"
}
],
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://URL",
"protocol": "http",
"host": [
"127",
"0",
"0",
"1"
],
"port": "8000",
"path": [
"api",
"MemberRegistration"
]
},
"description": "Registration API "
},
"response": []
}
]
}
]
}
It was because of sending same email address. Code is fine. Thanks

How i can read the nested properties and pushing to the array using javascript?

I want to read the JSON properties. if type is array or object or jsonp then i have to read the nested properties and need push it one array which should also be nested.
like:
{
name:"test",
type:"array"
[name]: {
name: "test1",
type: "..."
}
}
JSON object to read:
{
"properties": {
"value": {
"type": "array",
"items": {
"required": [
"#odata.etag",
"id",
"createdDateTime",
"lastModifiedDateTime",
"changeKey",
"originalStartTimeZone",
"originalEndTimeZone",
"iCalUId",
"reminderMinutesBeforeStart",
"isReminderOn",
"hasAttachments",
"subject",
"bodyPreview",
"importance",
"sensitivity",
"isAllDay",
"isCancelled",
"isOrganizer",
"responseRequested",
"showAs",
"type",
"webLink",
"isOnlineMeeting",
"onlineMeetingProvider",
"allowNewTimeProposals",
"isDraft",
"hideAttendees"
],
"properties": {
"id": {
"type": "string",
"minLength": 1
},
"end": {
"type": "object",
"required": [
"dateTime",
"timeZone"
],
"properties": {
"dateTime": {
"type": "string",
"minLength": 1
},
"timeZone": {
"type": "string",
"minLength": 1
}
}
},
"body": {
"type": "object",
"required": [
"contentType",
"content"
],
"properties": {
"content": {
"type": "string",
"minLength": 1
},
"contentType": {
"type": "string",
"minLength": 1
}
}
},
"type": {
"type": "string",
"minLength": 1
},
"start": {
"type": "object",
"required": [
"dateTime",
"timeZone"
],
"properties": {
"dateTime": {
"type": "string",
"minLength": 1
},
"timeZone": {
"type": "string",
"minLength": 1
}
}
},
"showAs": {
"type": "string",
"minLength": 1
},
"iCalUId": {
"type": "string",
"minLength": 1
},
"isDraft": {
"type": "boolean"
},
"subject": {
"type": "string",
"minLength": 1
},
"webLink": {
"type": "string",
"minLength": 1
},
"isAllDay": {
"type": "boolean"
},
"location": {
"type": "object",
"required": [
"displayName",
"locationType",
"uniqueIdType",
"address",
"coordinates"
],
"properties": {
"address": {
"type": "object",
"required": [],
"properties": {}
},
"coordinates": {
"type": "object",
"required": [],
"properties": {}
},
"displayName": {
"type": "string"
},
"locationType": {
"type": "string",
"minLength": 1
},
"uniqueIdType": {
"type": "string",
"minLength": 1
}
}
},
"attendees": {
"type": "array",
"items": {
"required": [
"type"
],
"properties": {
"type": {
"type": "string",
"minLength": 1
},
"status": {
"type": "object",
"required": [
"response",
"time"
],
"properties": {
"time": {
"type": "string",
"minLength": 1
},
"response": {
"type": "string",
"minLength": 1
}
}
},
"emailAddress": {
"type": "object",
"required": [
"name",
"address"
],
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"address": {
"type": "string",
"minLength": 1
}
}
}
}
},
"minItems": 1,
"uniqueItems": true
},
"changeKey": {
"type": "string",
"minLength": 1
},
"locations": {
"type": "array",
"items": {
"required": [],
"properties": {}
}
},
"organizer": {
"type": "object",
"required": [
"emailAddress"
],
"properties": {
"emailAddress": {
"type": "object",
"required": [
"name",
"address"
],
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"address": {
"type": "string",
"minLength": 1
}
}
}
}
},
"categories": {
"type": "array",
"items": {
"required": [],
"properties": {}
}
},
"importance": {
"type": "string",
"minLength": 1
},
"recurrence": {},
"#odata.etag": {
"type": "string",
"minLength": 1
},
"bodyPreview": {
"type": "string",
"minLength": 1
},
"isCancelled": {
"type": "boolean"
},
"isOrganizer": {
"type": "boolean"
},
"sensitivity": {
"type": "string",
"minLength": 1
},
"isReminderOn": {
"type": "boolean"
},
"hideAttendees": {
"type": "boolean"
},
"onlineMeeting": {},
"transactionId": {},
"hasAttachments": {
"type": "boolean"
},
"responseStatus": {
"type": "object",
"required": [
"response",
"time"
],
"properties": {
"time": {
"type": "string",
"minLength": 1
},
"response": {
"type": "string",
"minLength": 1
}
}
},
"seriesMasterId": {},
"createdDateTime": {
"type": "string",
"minLength": 1
},
"isOnlineMeeting": {
"type": "boolean"
},
"onlineMeetingUrl": {},
"responseRequested": {
"type": "boolean"
},
"originalEndTimeZone": {
"type": "string",
"minLength": 1
},
"lastModifiedDateTime": {
"type": "string",
"minLength": 1
},
"allowNewTimeProposals": {
"type": "boolean"
},
"onlineMeetingProvider": {
"type": "string",
"minLength": 1
},
"originalStartTimeZone": {
"type": "string",
"minLength": 1
},
"reminderMinutesBeforeStart": {
"type": "number"
}
}
},
"minItems": 1,
"uniqueItems": true
},
"#odata.context": {
"type": "string",
"minLength": 1
},
"#odata.nextLink": {
"type": "string",
"minLength": 1
}
}
}
This code will return all the nested values
propertiesObj = "";// the above json
contextProperties = [];
generate_properties(propertiesObj, propertiesArray) {
Object.entries(propertiesObj).forEach(([key, value]) => {
// console.log(value);
let contextObj = {};
contextObj["attrName"] = key;
contextObj["attrId"] = key;
contextObj["datatype"] = value["type"];
contextObj["attrType"] = "output";
if (value["type"] == "array" || value["type"] == "object") {
contextObj[key] = [];
if (Object.keys(value).includes("items")) {
this.generate_properties(
value["items"]["properties"],
contextObj[key]
);
} else {
this.generate_properties(value["properties"], contextObj[key]);
}
propertiesArray.push(contextObj);
} else {
propertiesArray.push(contextObj);
}
});
}

ES6 Object Mapping

I was working on something but stuck at a point where I have inputs as -
var definition = [
{
"name": "objA",
"type": "object",
"items": [
{
"value": "",
"name": "A"
},
{
"value": "",
"name": "B"
},
{
"value": "",
"name": "C"
}
]
},
{
"name": "objX",
"type": "object",
"items": [
{
"value": "",
"name": "X"
},
{
"value": "",
"name": "Y"
},
{
"value": "",
"name": "Z"
}
]
}
];
var data = {
"objA": {
"A": "ValA",
"B": "ValB",
"C": "ValC"
},
"objX": {
"X": "ValX",
"Y": "ValY",
"Z": "ValZ"
}
};
const updateSchema = (data, definition) => {
definition.forEach((subDef) => {
var node = data[subDef.name];
subDef.items.forEach((sub)=> {
sub.value = node[sub.name]
});
});
return definition;
}
console.log(updateSchema(data,definition))
The output I need is
[
{
"name": "objA",
"type": "object",
"items": [
{
"value": "valA",
"name": "A"
},
{
"value": "valB",
"name": "B"
},
{
"value": "valC",
"name": "C"
}
]
},
{
"name": "objX",
"type": "object",
"items": [
{
"value": "valX",
"name": "X"
},
{
"value": "valY",
"name": "Y"
},
{
"value": "valZ",
"name": "Z"
}
]
}
]
But it gives the output as -
[
{
"name": "objA",
"type": "object",
"items": [
{
"value": "ValX",
"name": "A"
},
{
"value": "ValY",
"name": "B"
},
{
"value": "ValY",
"name": "C"
}
]
},
{
"name": "objX",
"type": "object",
"items": [
{
"value": "ValX",
"name": "X"
},
{
"value": "ValY",
"name": "Y"
},
{
"value": "ValZ",
"name": "Z"
}
]
}
]
I am not able to know where I am doing wrong.
I am using React with typescript. I need to perform the above operation based on some API response.
I am prepopulating some value in the form based on the API response.
Try:
subDef.items.forEach((sub)=> {
sub.value = node[sub.name].charAt(0).toLowerCase() + node[sub.name].slice(1);
});
https://jsfiddle.net/j8nwpf6m/

Categories

Resources