I have this object example:
{
"id": 1,
"name": "name",
"address": "add",
"contactsArr": [{
"id": 1,
"name": "cont",
"tel": "tel",
"mail": "mail"
}],
"description": "desc"
}
this object is inside an array of objects, the array is called arrSuppCompNames. I get this array from a JSON string inside a DB table.
here is my function to get the last object's id inside contactsArr:
function getLastIdFromArrContUser(){
if("{{user.supplier_comp_name}}" != null && "{{user.supplier_comp_name}}" != "" && "{{user.supplier_comp_name}}" != 0){//not first
var arrSuppCompNames = JSON.parse(("{{user.supplier_comp_name}}").replace(/"/g,'"'));
console.log("arrSuppCompNames: " + JSON.stringify(arrSuppCompNames));
return arrSuppCompNames[arrSuppCompNames.length - 1].contactsArr[contactsArr.length - 1].id;
}else{//first
return 0;
}
}
but I keep getting Uncaught ReferenceError: contactsArr is not defined in this line return arrSuppCompNames[arrSuppCompNames.length - 1].contactsArr[contactsArr.length - 1].id;. the thing is I know for sure that contactsArr exists inside the array of objects because of the log print just a line before. this is my log:
arrSuppCompNames: [{"id":1,"name":"name","address":"add","contactsArr":[{"id":1,"name":"cont","tel":"tel","mail":"mail"}],"description":"desc"}]
Don't know if it's just a stupid JS error or mistype I can't see or something more JSON related.
Your try to access index [contactsArr.length - 1] but contactsArr is not defined in this context. Consider:
var contactsArr = arrSuppCompNames[arrSuppCompNames.length - 1].contactsArr;
return contactsArr[contactsArr.length - 1].id;
Based on your example I don't think you need to specify the index on contactsArr. It should just be return arrSuppCompNames[arrSuppCompNames.length - 1].contactsArr.id;
You can use destructing assignment to get "contactsArr" property value array containing "id" property
var arrSuppCompNames = [{
"id": 2,
"name": "name",
"address": "add",
"contactsArr": [{
"id": 2,
"name": "cont",
"tel": "tel",
"mail": "mail"
}],
"description": "desc"
},
{
"id": 1,
"name": "name",
"address": "add",
"contactsArr": [{
"id": 1,
"name": "cont",
"tel": "tel",
"mail": "mail"
}],
"description": "desc"
}
]
var {contactsArr: [{id}]} = arrSuppCompNames[arrSuppCompNames.length - 1];
console.log(id);
Related
I'm running a node.js server that sends queries to an elasticsearch instance. Here is an example of the JSON returned by the query:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
I need to create an array containing each job title as a string. I've run into this weird behavior that I can't figure out. Whenever I try to pull values out of the JSON, I can't go below options or everything comes back as undefined.
For example:
arr.push(results.suggest.postSuggest) will push just what you'd expect: all the stuff inside postSuggest.
arr.push(results.suggest.postSuggest.options) will come up as undefined even though I can see it when I run it without .options. This is also true for anything below .options.
I think it may be because .options is some sort of built-in function that acts on variables, so instead of seeing options as JSON and is instead trying to run a function on results.suggest.postSuggest
arr.push(results.suggest.postSuggest.options)
postSuggest is an array of object.options inside postSuggest is also array of object. So first you need to get postSuggest by postSuggest[0] and then
postSuggest[0].options to get array of options
This below snippet can be usefule
var myObj = {..}
// used jquery just to demonstrate postSuggest is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
document.write("<pre>Score is "+ item.score + " Text</pre>")
})
Jsfiddle
I need to replace multiple occurrence of property value in a json request using JavaScript. I have tried this in JSFiddle and it worked but the same code in an Apigee JavaScript policy is not replacing the value.
I have json data as follows:
[
{
"Name": "app1",
"groups": [
{
"desc": "this is a test group",
"id": "test1",
"name": "test grp45"
},
{
"desc": "this is another test group",
"id": "test2",
"name": "test group 2"
}
],
"id": "1"
},
{
"Name": "app2",
"groups": [
{
"desc": "this is a test group",
"id": "test3",
"name": "test group 4"
},
{
"desc": "this is another test group",
"id": "test4",
"name": "test group 4"
}
],
"id": "2"
},
{
"Name": "app3",
"groups": [
{
"desc": "this is a test group",
"id": "test5",
"name": "test group 5"
},
{
"desc": "this is another test group",
"id": "test6",
"name": "test group 6"
}
],
"id": "3"
}
]
Here's what I have tried:
var val = context.getVariabl("request.content");
context.setVariable("val", val);
function findAndReplace(val1, value, replacevalue) {
for (var x in val1) {
if (typeof val1[x] == typeof {}) {
findAndReplace(val1[x], value, replacevalue);
}
if (val1[x] == value) {
val1["name"] = replacevalue;
//break; // uncomment to stop after first replacement
}
}
}
findAndReplace(val, "test1", "img");
var result = JSON.stringify(val);
var obj = JSON.parse(result);
context.setVariable("response.content", obj);
I want to replace the value of "test1" to "img".
First, you're setting response.content with the parsed obj. You'd want:
context.setVariable("response.content", result);
...instead, because the flow variable needs to be a string, not a JavaScript object.
Second, you're getting request.content and then setting response.content. You probably only want one or the other, especially considering that likely this policy is attached to the request OR the response flow, not both (you can't set the request in the response flow, and content.response would be overwritten by the target response).
Use the Apigee trace tool to see where in the flow your policy is executing, and to inspect the variables being set -- this will help you figure out what you need to fix.
As suggested above you have a couple of things to do to get this to work.
First I would suggest you use two policies. The javascript sample above would be called in the request flow - the one above would store a stringified version of the object into an intermediate flow variable say "foo" as below:
var val = JSON.parse(context.getVariable("request.content"));
findAndReplace(val, "test1", "img");
context.setVariable("foo",JSON.stringify(val));
In the response flow you can then use an assign message policy to insert "foo" into the response. As below:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="assignFoo">
<DisplayName>assignFoo</DisplayName>
<FaultRules/>
<Properties/>
<Set>
<Headers/>
<Payload contentType="application/json; charset=utf-8">{foo}</Payload>
<StatusCode>200</StatusCode>
<ReasonPhrase>OK</ReasonPhrase>
</Set>
<AssignTo createNew="false" transport="http" type="response" />
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</AssignMessage>
Use string replace()
This converts the JSON into string
JSON.stringify(json).replace("test1", "img")
and then you could convert it back to JSON with replaced values
JSON.parse(json)
[
{
"id": 1,
"title": "my Item",
"body": ""
},
{
"id": 2,
"title": "my Item 2",
"body": ""
},
{
"id": 3,
"title": "my Item 3",
"body": ""
}
]
Is above json structure good for storing says users viewed books? I have other key like users' setting so I try to nested/group things to be neater. My question is how can I check an object with value exist or not so I won't insert duplicated data. How to check the id 2 is existed in this case? Do I have to loop?
Do I have to loop?
Yes you have to loop ( or use a method which will do it) :
var idToCheck="id";
var valToCheck=2;
var a = your array...
var wasFound=false;
a.forEach(function(entry) {
if (entry[idToCheck]==valToCheck)
{
wasFound=true;
return;
}
});
//do whatever with `wasFound`.
http://jsbin.com/jigefamiqu/1/edit
I need to remove an object from an JSON tree. I know a reference to that object. Is there a nice way to do it via JavaScript or jQuery besides traversing the whole tree?
Example:
party = {
"uuid": "4D326531-3C67-4CD2-95F4-D1708CE6C7A8",
"link": {
"rel": "self",
"href": "http://localhost:8080/cim/party/4D326531-3C67-4CD2-95F4-D1708CE6C7A8"
},
"type": "PERSON",
"name": "John Doe",
"properties": {
"CONTACT": [
{
"category": "CONTACT",
"type": "EMAIL",
"key": "email",
"value": "john.doe#doe.at",
"id": "27DDFF6E-5235-46BF-A349-67BEC92D6DAD"
},
{
"category": "CONTACT",
"type": "PHONE",
"key": "mobile",
"value": "+43 999 999990 3999",
"id": "6FDAA4C6-9340-4F11-9118-F0BC514B0D77"
}
],
"CLIENT_DATA": [
{
"category": "CLIENT_DATA",
"type": "TYPE",
"key": "client_type",
"value": "private",
"id": "65697515-43A0-4D80-AE90-F13F347A6E68"
}
]
},
"links": []
}
And i have a reference: contact = party.properties.contact[1]. And I want to do something like delete contact.
You may delete it this way. I just tested it.
var party = {
// ...
}
alert(party.properties.CONTACT[0]) // object Object
delete party.properties.CONTACT[0] // true
alert(party.properties.CONTACT[0]) // undefined
Fiddle
UPDATE
In the case above party is a direct property of window object
window.hasOwnProperty('party'); // true
and that's why you can't delete a property by reference. Anyhow, behavior of delete operator with host objects is unpredictable. Though, you may create a scope around the party object and then you'll be allowed to delete it.
var _scope = {};
var _scope.party = {
// ...
};
var r = _scope.party.properties.CONTACT[0];
window.hasOwnProperty('party'); // false
alert(r) // object Object
delete r // true
alert(r) // undefined
It only works one way: a variable holds a reference, but there is no way given a particular reference to infer what variables hold it (without iterating over them and comparing).
I am getting a JSON in response from server:
{
"width": "765",
"height": "990",
"srcPath": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_MERGED_/1273.pdf",
"coverPage": "",
"documents": [
{
"index": "1",
"text": "Archiving Microsoft® Office SharePoint® Server 2007 Data with the Hitachi Content Archive Platform and Hitachi Data Discovery for Microsoft SharePoint",
"type": "doc",
"id": "HDS_054227~201106290029",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_2.png"
}
]
},
{
"index": "11",
"text": "Brocade FCoE Enabling Server I/O Consolidation",
"type": "doc",
"id": "HDS_053732~201105261741",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_2.png"
}
]
}
]
}
And I want to get pagelocation of the children.
Can anyone tell me how to do this?
Hi
i also want to get indexes from this and then want to get pagelocations of that particular children. Can you tell me how would i do that?
And also when i when i am getting indexes array it is returning me ,, only and not the index nos.
I am using following code for that :
indexes=response.documents.map(function(e){ return e.children.index; })
Thanks & Regards
If you're interested in simply retrieving all the page locations, you can do it using filter:
var locations = [];
json.documents.forEach(function(e,i) {
e.children.forEach(function(e2,i2) {
locations.push(e2.pageLocation);
)}
});
// returns flat array like [item1,item2,item3,item4]
You can get an array of arrays using map:
var locations = [];
var locations = json.documents.map(function(e) {
return e.children.map(function(e2) {
return e2.pageLocation;
});
});
// returns 2-dimensional array like [[item1,item2],[item1,item2]]
Your json response is an appropriate javascript object So you can access all elements of the object like you do as in back end.
here, you have an array of object of the type documents and each document object has array of objects of the type children. so
syntax would be
myjson.documents[0].children[0].pagelocation
( = http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png)
will give you the very first page location..
and so on