pushing items to object array - javascript - javascript

Update: I'm trying to construct a table out of my data structure(ie section1) and then allow users to add rows to the table to insert more rows and save them to my datastructure.
I have an array newArr in the form of key value pairs. When somebody clicks a button, I want to be able to push the newArray into the Groups.I dont seem to be able to push into the Groups array. Chrome dev tools shows Groups as Objects and i'm not certain how to loop through and append to each item of the Groups Object. Feel free to modify the $scope.section1 to a different datastructure that could make it easier to push new items to it.
$scope.section1 = [{
"id":1, "Name": "Section 1: Inventory",
"Groups":[
{"cell" : "Number", "cellValue" : "value1"},
{"cell" : "Location", "cellValue" : "value2"},
{"cell" : "Severity", "cellValue" : "value3"}
],
"FootNotes":[
{"templateurl" : "components/section/templates/notes/section1.notes.html"}
]
}]
var newArr = {"cellValue" : "value4","cellValue" : "value5","cellValue" : "value6"}
So the output should look like
$scope.section1 = [{
"id":1, "Name": "Section 1: Inventory",
"Groups":[
{"cell" : "Number", "cellValue" : "value1", "cellValue" : "value4"},
{"cell" : "Location", "cellValue" : "value2", "cellValue" : "value5"},
{"cell" : "Severity", "cellValue" : "value3", "cellValue" : "value6"}
],
"FootNotes":[
{"templateurl" : "components/section/templates/notes/section1.notes.html"}
]
}]

You can't have two properties with the same name. You have cellValue two times for Object group. What are you trying to do?
You'd better like to change the structure itself:
...
"Groups": [
{
name: "group1",
values: ['value 1', 'value 2', 'value 3']
}
]
Then, adding one more value to group1:
$scope.section1[0].Groups.values.push('value 4')
Note than I'm trying to respect the whole structure that you already have, but I don't meaning this is the optimal way to solve your problem

$scope.section1[0].Groups.push({
"cell" : "Number",
"cellValue" : "value1",
"anotherCellValue" : "value4"
});

Related

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));
});

Mongo: cross referencing values in other objects

I have a collection that looks like the ff:
{
"word":"approve",
"related" : [
{
"relationshipType" : "cross-reference",
"words" : [
"note"
]
},
{
"relationshipType" : "synonym",
"words" : [
"demonstrate",
"ratify",
]
}
],
},
{
"word": "note",
"related" : [
{
"relationshipType" : "synonym",
"words" : [
"butt",
"need",
],
},
{
"relationshipType" : "hypernym",
"words" : [
"air",
"tone",
]
},
{
"relationshipType" : "cross-reference",
"words" : [
"sign",
"letter",
"distinction",
"notice",
]
},
],
}
I want to group/categorize all the objects which have a word in another object, be it
the name (as the cross-reference field of 'approve', has note. searches for the word 'note'.
or
the word is in another object's related words. like having a synonym of 'ratify' under 'approve' then looking for other objects that have have 'ratify' in any field of their related words.
Then save these to a new collection called categories.
result should Be:
{
"category": 1,
"words":["approve","note"],
}
...and the value of the word field for all the linked objects in the words array.
Any way how to do this.. i'm thinking about some sort of recursion in checking links but i'm not sure how to implement. another potential problem is going back to the parent layer creating an infinite loop of sorts.
and is it possible through map reduce?
EDIT: clarity.

Jquery JSON decode multiple arrays

I have this multiple set of data as array
data = [{"id": "1", "name" : "abc", "key1" : "value12 }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
I need to get this data using jQuery
json = $.parseJSON(data);
but how do I access the parsed JSON data? json.id shows the result as undefined.
Thanks
Update : Sorry I fixed the above example JSON I gave, I just quickly typed it by myself and it's not the original json I'm having trouble with. I just gave it to give an idea about the problem that I was having. Thanks for the answers :)
It isn't JSON. It isn't even JavaScript.
If you fix the syntax errors (such as the missing quotes and the missing commas between the array items) then it is an array literal (containing object literals which contain …). Don't parseJSON it (you use that on JSON texts stored in JavaScript strings).
Since it is an array. It doesn't have an id. It has a number of numerical indexes.
var someObject = data[0];
The objects stored on those indexes have ids.
var id = someObject.id;
Your json is invalid. ',' are missing between objects.
Suppose if json is :
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }]
Then you can access 'id' element using this :
data[0].id
Try this:
var data = '{"id": "1", "name" : "abc", "key1" : "value12" } , {"id": "2", "name" : "cde", "key2" : "value2"}';
var obj = JSON.parse('[' + data + ']');
alert(obj[0].id);
Here is demo
Your json is invalid,
data = [{"id": "1", "name" : "abc", "key1" : "value12" }, {"id": "2", "name" : "cde", "key2" : "value2" }.....]
Retrive using:
var id = data[0].id;
console.log(id);

How to get json object key name from collection and iterate

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"]

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