I have a json array and I need to alert a value in it.
The object looks like this:
Test = [
{
"adj" : [
{
"nodeTo" : "x",
"nodeFrom" : y,
"data":
{
"$type" : "line",
"$color" : "#A989BC",
"$value" : "number"
}
}
],
"id" : "id1",
"name" : "name1"
},
{
"adj" : [ ..... ] // I have many element in the Test array
What I want is to alert the value existed in the "data" array which exists in the "adj" array.
I tried this:
alert(Test[0]["adj"]["data"]["value"]);
But it isn't working.
Thanks in advance:)
adj is an array:
alert(Test[0]["adj"][0]["data"]["value"]);
Try this piece of code
alert(Test[0]["adj"][0]["data"]["value"]);
alert(Test[0]["adj"][0]["data"]["value"]);
There is an object after adj, so you need to add a [0]
alert(Test[0]["adj"][0]["data"]["value"]);
Related
I have a document in my mongo instance in below format,
{
"_id" : "08d4a242-08fb-07f7-46e5-8717a81d5b70",
"fname" : "john",
"created_date" : ISODate("2017-05-24T01:13:06.829Z"),
"customProp" : [
[
"customX","{\"some data related to X \"}"
],
[
"customY","{\"some data related to Y \"}"
],
[
"customZ","{\"some data related to Z \"}"
]
]
}
the elements/values like "customX","customY" & "customZ" are not necessarily be in all documents. How to retrieve all the values in second element of "customProp" array, in this document it contains "customZ"?
I'm able to use following query to filter & find all the documents which are having "customZ" element,
db.getCollection('col1').find({$and : [{"customProp":{$elemMatch:{0:"customZ"}}}, {"created": { $gte: ISODate("2017-05-22T00:00:00.000Z") }}] },{"created":1}).limit(1) .pretty()
output:
{
"_id" : "08d4a242-08fb-07f7-46e5-8717a81d5b45",
"created" : ISODate("2017-05-24T01:13:06.829Z")
}
but finding a way to retrieve all the values in second element of array where the first value is "customZ".
expected result:
{
"_id" : "08d4a242-08fb-07f7-46e5-8717a81d5b45",
"created" : ISODate("2017-05-24T01:13:06.829Z"),
"customPro": ["customZ","{\"some data related to Z \"}"]
}
I'm fine if my query just returns
{
"{\"some data related to Z \"}"
}
Well it is a nested array, which is not a great idea but you are in fact matching the element with the $elemMatch expression, so you do get the position in the "outer" array of customProp, which allows you to project with the positional $ operator:
db.getCollection('coll1').find(
{
"customProp":{ "$elemMatch": { "0": "customZ" } },
"created_date": { "$gte": ISODate("2017-05-22T00:00:00.000Z") }
},
{ "created_date": 1, "customProp.$": 1 }
)
That yields the result:
{
"_id" : "08d4a242-08fb-07f7-46e5-8717a81d5b70",
"created_date" : ISODate("2017-05-24T01:13:06.829Z"),
"customProp" : [
[
"customZ",
"{\"some data related to Z \"}"
]
]
}
Where customProp is of course still in a nested array, but when processing the individual documents in python you can just access the property at the array index:
doc['customProp'][0][1]
Which of course returns the value:
'{"some data related to Z "}'
Same goes for JavaScript really, which is basically identical in syntax. As a shell example:
db.getCollection('coll1').find(
{
"customProp":{ "$elemMatch": { "0": "customZ" } },
"created_date": { "$gte": ISODate("2017-05-22T00:00:00.000Z") }
},
{ "created_date": 1, "customProp.$": 1 }
).map(function(doc) {
doc['customProp'] = doc['customProp'][0][1];
return doc;
})
And the output:
{
"_id" : "08d4a242-08fb-07f7-46e5-8717a81d5b70",
"created_date" : ISODate("2017-05-24T01:13:06.829Z"),
"customProp" : "{\"some data related to Z \"}"
}
And the positional $ projection here ensures there is only one element in the returned array, so the notation is always the same to extract from all document results. So you get the matched element from the database, and you extract the property through the code.
Also note that you do not need $and here since all the query arguments are already AND conditions. This is the MongoDB default, so you do not need to explicitly express it. See how much nicer this looks without it.
My JSON currently looks like this:
{
"_id" : 393,
"item" : 34,
"comments" : [
{
"name" : "kevin",
"messages" : [
"item",
"item"
]
},
{
"name" : "ryan",
"messages" : [
"item",
"item"
]
}
]
}
How could I push new items onto the messages array for the first or second item in the comments array?
db.newcon.update({_id: 393}, { $push: { comments['kevin']: {messages: 39 } } })
Using $elemMatch and $ operator you can update your documents check below query :
db.collectionName.update({"_id":393,"comments":{"$elemMatch":{"name":"kevin"}}},
{"$push":{"comments.$.messages":39}})
Something like this will work:
var newMessage = '39';
comments.forEach(function(item) {
if (item.name === 'kevin') {
item.comments.push(newMessage);
}
});
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"]
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
Square brackets is an array, and curly brackets are objects correct?
What exactly is this data structure:
Some.thing = [ {
"swatch_src" : "/images/91388044000.jpg",
"color" : "black multi",
"inventory" : {
"F" : [ 797113, 797114 ],
"X" : [ 797111, 797112 ]
},
"images" : [ {
"postfix" : "jpg?53_1291146215000",
"prefix" : "/images/share/uploads/0000/0000/5244/52445892"
}, {
"postfix" : "jpg?53_1291146217000",
"prefix" : "/images/share/uploads/0000/0000/5244/52445904"
}, {
"postfix" : "jpg?53_1291146218000",
"prefix" : "/images/share/uploads/0000/0000/5244/52445909"
} ],
"skus" : [ {
"sale_price" : 199,
"sku_id" : 797111,
"msrp_price" : 428,
"size" : "s"
}, {
"sale_price" : 199,
"sku_id" : 797112,
"msrp_price" : 428,
"size" : "m"
}, {
"sale_price" : 199,
"sku_id" : 797113,
"msrp_price" : 428,
"size" : "l"
}, {
"sale_price" : 199,
"sku_id" : 797114,
"msrp_price" : 428,
"size" : "xl"
} ],
"look_id" : 37731360
} ];;
Some.thing is an array [] containing a single object {}. Some of the properties of this object are strings while others are arrays.
The single object appears to be describing a product.
Yes, an array of objects with nested arrays within. (or in this case one single element contained within an array.)
Some.thing[0] refers to everything you have listed. From there, you have an object containing:
var obj = Some.thing[0];
obj.swatch_src // contains "/images/91388044000.jpg"
obj.color // contains "black multi"
...
obj.inventory // (another object
obj.inventory.F // array of [797113, 797114]
...
obj.images // array of objects
obj.images[0].postfix // contains "jpg?53_1291146215000"
obj.images[0].prefix // contains "/images/share/uploads/0000/0000/5244/52445892"
...
This is captured from Chrome Console. You can try it yourself :)
Yes, this is called JSON: JavaScript Object Notation.