Sorting a JSON array and echoing out with $.each - javascript

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.

Related

Dynamically add array elements to JSON Object

I'm creating a JSON object from an array and I want to dynamically push data to this JSON object based on the values from array. See my code for a better understanding of my problem...
for(i=0;i<duplicates.length; i++) {
var request = {
"name": duplicates[i].scope,
"id": 3,
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
I take object properties from the duplicates array that can have the following elements:
[{scopeDef=.*, scope=Global, variable=[trackingcode, v1, v2]}, {scopeDef=^https?://([^/:\?]*\.)?delta.com/products, scope=Products Section, variable=[v3]}]
As you can see, an object contain variable element that can have multiple values. I need to push to the JSON object all those values dynamically (meaning that there could be more than 3 values in an array).
For example, after I push all the values from the duplicates array, my JSON object should look like this:
name=Products Section,
rules=
[
{
name=Products Section OP SDR Sync,
tags=[
{
variables=
[
{
matchType=Regex,
variable=v3,
value=^https?://([^/:\?]*\.)?delta.com/products
},
{
matchType=Regex,
variable=trackingcode,
value=.*
},
{
matchType=Regex,
variable=v1,
value=.*
},
{
matchType=Regex,
variable=v2,
value=.*
}
],
condition=false,
},
{
condition=false,
tagId=1
}
],
ruleSetId=3
}
]
}
I tried the following code but without success:
for(var j in duplicates[i].variable) {
var append = JSON.parse(request);
append['variables'].push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
}
Please let me know if I need to provide additional information, I just started working with JSON objects.
First of all, you dont need to parse request, you already create an object, parse only when you get JSON as string, like:
var json='{"a":"1", "b":"2"}';
var x = JSON.parse(json);
Next, you have any property of object wrapped in arrays. To correctly work with it you should write:
request.rules[0].tags[0].variables.push({
"variable":duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
})
If you want to use your code snippet, you need some changes in request:
var request = {
"name": duplicates[i].scope,
"id": 3,
"variables":[
{
"variable": duplicates[i].variable[j],
"matchType": "Regex",
"value": duplicates[i].scopeDef
}
],
"rules":[
{
"name": duplicates[i].scope + " " + "OP SDR Sync",
"tags": [
{
"tagId": 1,
"condition": false,
},
{
"tagId": 1,
"condition": false,
}
],
"ruleSetId": 3,
}
]
}
}
To understand JSON remember basic rule: read JSON backward. It means:
property
object.property
arrayOfObfects['id'].object.property
mainObject.arrayOfObfects['id'].object.property
and so on. Good luck!

Functional Javascript algorithm not returning the expected result from a filter

I am practicing using map(), filter(), and concatAll()in Javascript. I am expecting the code below to return the following:
[{
"id": 70111470,
"title": "Die Hard",
"boxart":"http://cdn-0.nflximg.com/images/2891/DieHard150.jpg"
}]
It is not pulling in the URL from the boxart and I am not sure why. I get the following output when I run my code:
[{"id": 70111470,"title": "Die Hard"}]
function() {
var movieLists = [
{
name: "Instant Queue",
videos : [
{
"id": 70111470,
"title": "Die Hard",
"boxarts": [
{ width: 150, height:200, url:"http://cdn-0.nflximg.com/images/2891/DieHard150.jpg" },
{ width: 200, height:200, url:"http://cdn-0.nflximg.com/images/2891/DieHard200.jpg" }
],
"url": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": 4.0,
"bookmark": []
}
]
}
];
getBoxart = function(boxart){
return boxart.width==150;
};
getVideoData = function(video){return {id: video.id,
title: video.title,
boxart: video.boxarts.filter(getBoxart).url}
};
getVideos = function(movie){return movie.videos.map(getVideoData)}
return movieLists.map(getVideos).concatAll();
}
the issue is this line: video.boxarts.filter(getBoxart).url
filter is returning an array of boxarts (which does not have a url property)
you either need to map after filter to return an array of urls, or just grab the first one
That's because
video.boxarts.filter(getBoxart)
returns an array (if that's the native implementation of filter, but probably for any other implementation as well), and then doing
video.boxarts.filter(getBoxart).url
returns undefined since arrays don't have a url property...
You probably need to do:
video.boxarts.filter(getBoxart)[0].url

compare 2 array of objects. match by ids, push object property into array

I have 2 arrays. users and posts. posts contain a property "post_by" which is the id of one of the users. I need to match the user and push the first & last name into the post object as a new property. Goal is I need to display the name of the user that made the post in a table.
note* I can use javascript, jquery, linq.js or lodash.
fiddle with json
fiddle
var users = [
{
"id": "15e640c1-a481-4997-96a7-be2d7b3fcabb",
"first_name": "Kul",
"last_name": "Srivastva",
},
{
"id": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd",
"first_name": "Rudy",
"last_name": "Sanchez",
},
{
"id": "636f9c2a-9e19-44e2-be88-9dc71d705322",
"first_name": "Todd",
"last_name": "Brothers"
},
{
"id": "79823c6d-de52-4464-aa7e-a15949fb25fb",
"first_name": "Mike",
"last_name": "Piehota"
},
{
"id": "e2ecd88e-c616-499c-8087-f7315c9bf470",
"first_name": "Nick",
"last_name": "Broadhurst"
}
]
var posts = [
{
"id": 1,
"status": "Active",
"post_title": "test title",
"post_body": "test body",
"post_by": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd"
},
{
"id": 2,
"status": "Fixed",
"post_title": "test title two",
"post_body": "test body two",
"post_by": "79823c6d-de52-4464-aa7e-a15949fb25fb"
}
]
https://jsfiddle.net/zy5oe25n/7/
console.log($.map(posts, function(post){
var user = $.grep(users, function(user){
return user.id === post.post_by;
})[0];
post.first_name = user.first_name;
post.last_name = user.last_name;
return post;
}));
Here's a lodash approach:
_.map(posts, function(item) {
return _.assign(
_.pick(_.find(users, { id: item.post_by }),
'first_name', 'last_name'),
item
);
});
It's using map() to map the posts array to a new array of new objects (immutable data). It's then using find() to locate the user object, and uses pick() to get the properties we need. Finally, assign() adds the post properties to the new object that pick() created.
For good measure, using linq.js.
var userMap = Enumerable.From(users).ToObject("$.id");
posts.forEach(function (post) {
var user = userMap[post.post_by];
if (user) {
post.first_name = user.first_name;
post.last_name = user.last_name;
}
});
Note, we're using the builtin forEach() for arrays, linq.js is not needed for that part.

check json object exist to be save into localstorage

[
{
"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

JSON parsing in JS

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

Categories

Resources