How to get json object key name from collection and iterate - javascript

Below is my json structure. On success of collection.fetch() i'm looping through the structure.
Currently i use
this.collection.each(function(model) { .. }
How do i obtain key name like plants, animals and instead loop using the names.
JSON
var jsonObj = { // 0 - recommended , 1 - New
"plants" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
],
"animals" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
]
};
Snapshot of collection

This would work, but you'd use a normal for loop, not "each":
for(i in jsonObj){
alert(i);
}
here is a fjsfiddle: http://jsfiddle.net/r5nwP/
Is that what you're after?

You can use the underscore keys to get a list of names:
var thenames =_.keys(yourobject);
In this case thenames will contain a list of the keys you are looking for. Here is the documentation for it:
http://underscorejs.org/#keys
keys_.keys(object)
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

Related

Intersperse elements into array but if array is too long, split it up

I have a Set of userId strings like this:
["1", "2", "3"....]
I want to loop over and convert them to this object format:
[
{
"field" : "tag",
"key" : "user_id",
"relation": "=",
"value" : 1 // Insert userId here
},
etc...
]
And then in between the userId objects I need to add the object:
{ "operator": "OR" }
So the array looks like
[{userId object}, {OR object}, {userId object}, etc...]
There are an arbitrary number of userIds - there could be thousands. What I need to happen is, if there are more than 200 objects in the array, I need to call the function sendObjects(array) with that object array, and then reset the array and continue from where I left off. The array must not end in an OR object. How to do this??
Use forEach() on array numArray:
var numArray = ["1", "2", "3"];
var res = [];
numArray.forEach(function(val, index){
var obj = {
"field" : "tag",
"key" : "user_id",
"relation": "=",
"value" : val
};
res.push(obj);
if(numArray.length-1 !== index){
res.push({ "operator": "OR" });
}
});
console.log(res);

Retrieve Object from complex Array

I have this array :
var hemicycle = {
Group1 : [{
GroupName : "Les bests",
Member1 : [{
Name : "Loris Plasson",
Seat : 4,
Vignette : "PhotoURL"
}],
Member2 : [{
Name : "Anne-Sophie",
Seat : 3,
Vignette : "PhotoURL"
}]
}]
I want to push the object Member1 or Member2 on another object depending of the Seat value.
To do that I think I need to "search" for the Seat value with a for loop and retrieve the object, but all the examples I found on StackOverflow were with simple arrays like this :
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
With those simple arrays they are able to use something like a for loop with array[i].
But in my case I really don't know what to do...
UPDATE : What I want : The Member object which include the corresponding Seat value searched. Then I push the Member object to another object.
Thanks for any help.
The data structure that you use doesn't reflect what you are trying to convey, and in addition is very heard to traverse.
I suggest creating an array of groups. Each group is an object, that has the members property, which is an array of member objects:
[{
"GroupName": "Les bests",
"members": [{
"Name": "Loris Plasson",
"Seat": 4,
"Vignette": "PhotoURL"
},
{
"Name": "Anne-Sophie",
"Seat": 3,
"Vignette": "PhotoURL"
}
]
}]
Using this structure, you find a member using 2 for loops - one to iterate the groups, and the other to iterate the members of each group. Once a member is found, the function returns the member's object immediately. If not undefined is returned:
var groups = [{"GroupName":"Les bests","members":[{"Name":"Loris Plasson","Seat":4,"Vignette":"PhotoURL"},{"Name":"Anne-Sophie","Seat":3,"Vignette":"PhotoURL"}]}];
var seatNum = 4;
function findMember(seatNum) {
var members;
for(var i = 0; i < groups.length; i++) {
members = groups[i].members;
for(var j = 0; j < members.length; j++) {
if(members[j].Seat = seatNum) {
return members[j];
}
}
}
}
var member = findMember(seatNum);
console.log(member);

Addressing Objects in a JSON Array

I'm sending a JSON array to a script for further processing. The JSON array contains a bunch of objects each of which contain a further array of objects. What I need to know is how to access values within those nested objects. So, for instance, if the script receives the following:
petlist = [
{"cats":[
{"catName":"Felix","catType":"British short haired"}
]
},
{"dogs":[
{"dogName":"Fido","dogType":"Labrador"}
]
},
{"fish":[
{"fishName":"Bob","fishType":"Goldfish"}
]
},
{"birds":[
{"birdName":"Polly","birdType":"Parrot"}
]
}
]
How would I then address, say, a) dogName, b) birdType, or c) the entire cats object?
Also, am I correct in my terminology here? As I understand it the stuff in square brackets is an array, while the stuff in curly braces is an object.
edit: I am building the JSON in Javascript and I then need to access the elements in a Jade template (in an 'each' loop)
Thanks
I changed your JSON a little bit because I think it was not very fun to work with. Basically I just loop through the objects thats why I thought you should have a key like name instead of dogName, catName and so on.
You can find the working example with Jade in this JSFiddle
HTML
<div id="jadeoutput"></div>
<pre id="jadeinput" style="display:none">
- console.log(petlist)
h1 List
ul.list
- for(var i in petlist)
li= "Item - "+ petlist[i].name
- for(var j in petlist[i].pets)
li= "Pet - " + petlist[i].pets[j].name + " " + petlist[i].pets[j].type
</pre>
JavaScript
$(function() {
var json = {
"petlist" : [
{
"name" : "cats",
"pets":
[
{ "name":"Felix","type":"British short haired"}
]
},
{
"name" : "dogs",
"pets":
[
{"name":"Fido","type":"Labrador"}
]
},
{
"name" : "fish",
"pets":
[
{"name":"Bob","type":"Goldfish"}
]
},
{
"name" : "birds",
"pets" :
[
{"name":"Polly","type":"Parrot"}
]
}
]};
$("#jadeoutput").html(jade.compile($("#jadeinput").html())(json));
});

Javascript, deep extend

So I have an object I'm trynig to deep extend into - right now the extend function works if the lowest level is just an array, So it looks like this :
function(base, next) {
var dataEntry = base.filter(function(it) {
return it.module === next.module;
})[0];
if (dataEntry) {
var diff = next.customUrl.filter(function(it) {
return dataEntry.customUrl.indexOf(it) === -1;
});
dataEntry.customUrl = dataEntry.customUrl.concat(diff).sort();
//_.extend(dataEntry, next);
} else {
base.push(next);
}
}
And this works if the object looks like :
[
{"name" : "one", "test" : ["1","2"]},
{"name" : "two", "test" : ["1","2"]}
]
However some things had to change and now the object looks like this :
[
{"name" : "one", "test" : [{"random1" : true},{"random2" : false}] },
{"name" : "two", "test" : [{"random3" : true},{"random4" : false}]}
]
Where the keys in the array is now an array of objects, and the objects keys are random. So If there was an object with the same key - replace the value (unless its the same, otherwise push a new object inside of there.
So for that object above I would pass this to merge into it for example:
{"name" : "one", "test" : [{"random2" : true}]}
So that would change the value of random2 to true, or something like this
{"name" : "one", "test" : [{"random18" : true}] }
where that would push in random 18 like so :
[
{"name" : "one", "test" : [{"random1" : true},{"random2" : false},{"random18" : true}] },
{"name" : "two", "test" : [{"random3" : true},{"random4" : false}]}
]
Unsure how to traverse deeper and merge. Thanks for reading!!
Edit : first stab at it -
function(base, next) {
var dataEntry = base.filter(function(it) {
return it.module === next.module;
})[0];
if (dataEntry) {
var allTags = [];
allTags.push.apply(allTags, dataEntry.customUrl);
allTags.push.apply(allTags, next.customUrl);
dataEntry.customUrl = allTags;
} else {
base.push(next);
}
}
Does not work because it does not cover over objects if they are the same, just pushes into array.
http://jsfiddle.net/p08ayvv8/
this fiddle shows you how jQuery can deal with (deep) extending objects.
See http://api.jquery.com/jquery.extend/ for a detailed explaination.
It is mentionable though that when preforming the second extension jQuery will prepend the old value of test to the array, thats why I added
o1.test = o1.test[0];

Ordering JSON Objects using jQuery

I have the following JSON Object being loaded into my application and stored into a var called obj:
{
"items" : [
{
"name" : "item-1",
"group" : [
{
"groupName" : "name-1",
"groupPosition" : 2
},
{
"groupName" : "name-2",
"groupPosition" : 1
}]
},
{
"name" : "item-2",
"group" : [
{
"groupName" : "name-1",
"groupPosition" : 1
},
{
"groupName" : "name-2",
"groupPosition" : 2
}]
}]
}
I then do the following to go through it:
var groups = new Array();
var items = new Array();
$.each(obj.items, function(i,r){
var itemName = r.name;
$.each(r.group, function(index, record){
if ($.inArray(record.groupName) == -1) {
groups.push(record.groupName);
$('body').append('<div id="record.groupName"></div>');
}
$('#'+record.groupName).append('<div id="itemName">itemName</div>');
// At this point I'm stuck as the items get added in order of iteration,
// not according to their record.groupPosition value.
});
});
There will eventually be several hundred "items" each contained within an unset number of "groups".
The trouble I'm having is how to iterate through the JSON object using jQuery or good ol'JavaScript and display the items in the correct position within each group as the items and groups won't be listed inside the JSON object in sequential order.
Any help would be greatly appreciated!
Thank you.
Why not just give the group items the position index like this:
{
"items" : [
{
"name" : "item-1",
"group" : {
2:{
"groupName" : "name-1",
"groupPosition" : 2
},
1:{
"groupName" : "name-2",
"groupPosition" : 1
}}
},
{
"name" : "item-2",
"group" : {
1:{
"groupName" : "name-1",
"groupPosition" : 1
},
2:{
"groupName" : "name-2",
"groupPosition" : 2
}}
}]
}
Assuming you have a variable which is assigned to this:
var data = ...
you could use the $.each() method:
$.each(data.items, function(index, item) {
// here item.name will contain the name
// and if you wanted to fetch the groups you could loop through them as well:
$.each(item.group, function(i, group) {
// here you can use group.groupName and group.groupPosition
});
});
Arrays ([]) in javascript are 0 index based and preserve their order when you are iterating over them.
If I understood correctly your problem it is not about the sorting it self but how to link them to your dom nodes, solution: use classes with numbers.
For example:
$(".group"+items[1].group[0].grouposition").append(items[1].group[0].name);
// this will give append to the element with class="group1"
If you join this with having the html structure that is being generated to match the same names, then it won't be a problem and you don't have to sort them

Categories