[
{
"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
Related
I have a json array which im getting my react data from it,
the json is like this:
{
"Folders": [
{
"name": "parent 2",
"children": [ //this is children_1
{
"name": "parent 2",
"id": "parent 2",
"children": [] //this is children_2
}
],
"id": 1
}
]
}
lets say i have the key value of name inside children(children_1) and i want to get the rest of the data inside that children using the name that i have, is there a way to do that ?
Look at jsonpath
so it will be
var json = require('jsonpath');
var names = jp.query(json, '$.Folders[*].children[*].children');
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);
So currently I have a JSON array that looks like this
"series": [{
"book": 1,
"chapter": 1,
"title": "Title of this chapter",
},
{
"book": 1,
"chapter": 2,
"title": "Title of this chapter",
},
{
"book": 1,
"chapter": 3,
"title": "Title of this chapter",
},
{
"book": 2,
"chapter": 1,
"title": "Title of this chapter",
},
{
"book": 2,
"chapter": 2,
"title": "Title of this chapter",
}]
I need to echo it out with jQuery so I can do $.each for each book and within that do an $.each for each chapter.
Currently I have done $.each and then appended the results to the page and then tried to sort it with an external jQuery plugin, but to no avail.
With that JSON, you'll need to create an intermediate array of books to group together all the chapters of a given book. Then, on that intermediary structure (which is now an array of book objects) you can loop over them and spit out the chapters.
var json = //your JSON object
var books = {};
$.each(json.series,function(i,book) {
if(!books.hasOwnProperty(book.book)) {
books[book.book] = [];
}
books[book.book].push(book);
});
//now that you have each book in it's own array
$.each(books,function(i,book) {
$.each(book,function(i,chapter) {
console.log('Book ' + chapter.book + ', Chapter ' + chapter.chapter + ':' + chapter.title);
});
});
If it's at all possible that your books/chapters are not in order, then you'll need to sort them first. Starting with your original JSON object:
json.series.sort(function(a,b) {
return a.book-b.book || a.chapter-b.chapter;
});
Try this :
var json = '{"series":[{"book":"1","chapter":"1","title": "Title of this chapter"},{"book":"2","chapter":"2","title": "Title of this chapter"}]}';
var serieslist = $.parseJSON(json);
var series_books = {};
$.each(serieslist.series, function(index,book){
series_books.push(book);
});
$.each(series_books,function(i,book) {
$.each(book,function(i,chapter) {
//do what you need to here ...
});
})
Hopefully this helps, use $.parseJSON to parse out the JSON string into usable objects, then manipulate them as you please.
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)
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