Using a variable to select a JSON array element - javascript

Is it possible to supply a variable to select a particular element within a JSON array element in order to select it?
Assuming I have many users:
"users": [
{ "id":"000000", "uname": "admin", "password": "admin", "phash": "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86",
"profile": {
"fullname" : "Admin Admin",
"datejoined": "01-01-2014",
"reputation": "100",
"displaypic": "http://www.google.com/logo.png",
"cart": {
"Cid" : "1000000",
"item": [
{ "Iid": "00000001", "quantity": "10" }
]
}
}
},
Is it possible to select the above element by supplying just the username using jQuery?
I have tried:
Note: uname in the jQuery is a variable with "admin" assigned
$.getJSON('ssUsers.json', function (data) {
$(data.users[uname].profile.cart.item).each(function () {
++cartItems;
});
With little luck:
[Error] TypeError: 'undefined' is not an object (evaluating 'data.users[uname].profile')

Using grep:
thisUser = $.grep(data.users, function(e) { return e.uname==uname});

Try this:
$.getJSON('ssUsers.json', function (data) {
for(i=0; i<data.users.length ; i++){
$(data.users[i].uname.profile.cart.item).each(function () {
++cartItems;
}
});

Related

Datatable search in nested table

I'm using metronic v5.0.7.1 i have a datatable which is contains nested array so i just want to search in this array.
I'm able to bind my case status like that;
{
field: 'case.case_status',
title: "Status",
}
there is my search field;
var query = datatable.getDataSourceQuery();
$('#m_form_durum').on('change', function () {
datatable.search($(this).val(), 'case.case_status');
}).val(typeof query.case.case_status !== 'undefined' ? query.case.case_status : '');
After that im getting this error "Cannot read property 'case_status' of undefined". How can I specify the nested field in this case?
By the way if I replace my field to 'count' which is in my array instead of 'case.case_status' its work very well. Just nested fields give this error.
Also this is my sample data:
[
{
"id": 93,
"case": {
"id": 99,
"case_status": 1,
},
"user": "1",
"count": "2",
"created_at": "2018-02-08T09:00:00.884590+03:00",
"modified_at": "2018-02-08T09:00:00.884612+03:00",
"is_deleted": false,
}
]

Drop-down empty selection from the menu

I work with a JavaScript app and populate the drop-down menu with a JSON list.
$("#address").append($('<option></option>').attr("value", "1").text(""));
$.each(wallets, function (index, wallet) {
if (selectedCurrency === wallet["currency"].toString().trim()) {
$("#address").append($('<option></option>').attr("value", "1").text(wallet["address"]));
}
})
The UI looks like this,
If I select the empty item (like in the picture), I would like to print empty in the console. Otherwise, I want to print the address value. My intention is to write more code, but, this is where I would like to get started. The code I have,
$("#address").change(function () {
if($(this).val()===""){
console.log('empty');
}
else{
console.log($(this).val());
}
}
However, it only prints 1 in the console and can't distinguish between the empty bar and the address in concern. If I use console.log("The value is " + $(this).text()); inside the change function, it prints every info all together in the console,
The value is mp51mPC38Wtcmybdyd9MPEB2bKnw6eYbCsmqXjM7Mmg6B5LWMad7mHJi339ddaj7xXdBmvXxP1GmXXKojWQJKjgeoASnXVNXCS47z6n41jE2BKKpV6LsPb7dDdStjtuJf1FrYvMMmw1jtrWU5DADxvNR421MKFW1fposgzVMBymnzcZVF4jtZtGAggM5GuLog3Y5o52Mx4xMmq5Rgggfgy2TiRsvtcGm3rxx12R8XbYi9omkdt7ouyJnDXUp4LzdRSRP3ZhU57gUDKy6n2F2QEKk6Fqqk2yMTope5MYp1RtpT949kemrkdfp6qoVN3YiyJhq6nXPvgr3f7YpkS9j
The JSON data I have is something like,
[
{
"id": 1,
"code": "BTC",
"address": "mp51mPC38Wtcmybdyd9MPEB2bKnw6eYbCs",
"currency": "Bitcoin"
},
{
"id": 2,
"code": "BTC",
"address": "mqXjM7Mmg6B5LWMad7mHJi339ddaj7xXdB",
"currency": "Bitcoin"
},
{
"id": 4,
"code": "BTC",
"address": "mvXxP1GmXXKojWQJKjgeoASnXVNXCS47z6",
"currency": "Bitcoin"
}
// some more data
]
What the issue here? My guess is I do something wrong to append the data to the drop-down list and needs to be changed.
I can provide more info if required ....
Just change the value 1 to "" in first option.
$("#address").append($('<option></option>').attr("value", "").text(""));
$.each(wallets, function (index, wallet) {
if (selectedCurrency === wallet["currency"].toString().trim()) {
$("#address").append($('<option></option>').attr("value", "1").text(wallet["address"]));
}
});
check this example.
$("#address").append($('<option></option>').attr("value", "").text(""));
$("#address").append($('<option></option>').attr("value", "1").text("123"));
$("#address").append($('<option></option>').attr("value", "2").text("456"));
$("#address").change(function () {
if($(this).val()===""){
console.log('empty');
}
else{
console.log($(this).val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="address">
</select>

Manipulating MongoDB response NodeJS

I made a "little" query for mongodb to join two collections and retrieve data.
The game: insert 2 or 3 params on a URL
-include can be 0,1 or 2.
0 exclusive
1 inclusive
2 return all
-netcode: is a key to filter data
-group: another optional keys, that works with the first param "include"
-My query works perfectly, returns in a way how much times a event happened in a certain group.
-The problem? I can't work with the result of mongo db, i need to parse it to JSON.
I'm not so clever at JS, so i don't know where to put it. Since i work in corporation, some of the code was already done.
Well my output is this:
{
"events": [
{
"_id": {
"group": "GFS-CAJEROS-INFINITUM-TELDAT-M1",
"event": "SNMP DOWN"
},
"incidencias": 1
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Input Utilisation"
},
"incidencias": 1209
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Output Utilisation"
},
"incidencias": 1209
},
{
"_id": {
"group": "GFS-CAJEROS-MPLS",
"event": "Proactive Interface Availability"
},
"incidencias": 2199
},
{
"_id": {
"group": "GFS-SUCURSALES-HIBRIDAS",
"event": "Proactive Interface Output Utilisation"
},
"incidencias": 10
},
But i want it fused in a JSON format, like this: check the int value is next for the name of the event.
[
{
"group": "GFS-CAJEROS-MPLS",
"Proactive Interface Input Utilisation" : "1209",
"Proactive Interface Output Utilisation" : "1209",
"Proactive Interface Availability" : "2199",
},
{
"group": "GFS-SUCURSALES-HIBRIDAS",
"Proactive Interface Output Utilisation" : "10",
},
I'm using Nodejs and the mongodb module, since i dont know how this function exactly works, i don't know how to manage the response, ¿there is a better way to do this? like to get the json file, using another js to generate it?
This is the code i'm using, basically is the important part:
var events = db.collection('events');
events.aggregate([
{ $match : { netcode : data.params.netcode } },
{
$lookup:
{
from: "nodes",
localField: "name",
foreignField: "name",
as: "event_joined"
}
},
{ $unwind: {path: "$event_joined"} },
{ $match : {"event_joined.group" :
{$in:
[
groups[0] ,
groups[1] ,
groups[2] ,
groups[3] ,
groups[4] ,
groups[5] ,
groups[6] ,
groups[7] ,
groups[8] ,
groups[9] ,
]
}
}
},
{ $group : { _id : {group:"$event_joined.group", event:"$event"}, incidencias: { $sum: 1} } },
])
.toArray( function(err, result) {
if (err) {
console.log(err);
} else if (result) {
data.response.events = result;
} else {
console.log("No result");
}
You should add another $group to your pipeline {_id: "$_id.group", events: {$push : {name: "$_id.event", incidencias: "$incidencias"}}}
Then change the structure of your data on the JS code with "Array.map".
data.response.events = data.response.events.map(function (eve){
var obj = {
"group": eve.group
};
eve.events.forEach(function (e){
obj[e.name] = e.incidencias
})
return obj;
})

Why is my Mongoose query not updating a value in a nested array in the MongoDB databse?

I have tried to implement this in several ways and none seem to work.
All I need to do is change the Status value of a specific Notifications object (found by its _id) from 0 to 1.
Example JSON:
{
"_id": "577fbf0c7c6e88600ede5e73",
"updatedAt": "2016-07-14T11:27:18.670Z",
"createdAt": "2016-07-08T14:56:12.013Z",
"Name": "Name",
"Email": "test#test.com",
"Notifications": [
{
"_id": "5787644108edec801e9cd0ab",
"Title": "They commented on This",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
},
{
"_id": "578777167d1f3424251c361f",
"Title": "He commented on That",
"Type": 1,
"Status": 0,
"TeamID": "578357109bb105602b1cba27",
"DraftID": "578357b89bb105602b1cba2a"
}
]
.....
}
My route:
router.post('/notification', function (req, res) {
UserProfile.update({
'Notifications._id' : req.body.NotificationID
}, {
'$set' : {
'Notifications.$.Status' : 1
}
}, function (err) {
if (err)
res.send(err);
})
});
I don't get any errors and the update doesn't seem to happen.
What could the problem be?
Is the type of Notifications._id ObjectId? If so, try cast req.body.NotificationId to ObjectId. Change the query to
{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}
Try '$set' instead of $set.
Ensure that you are getting id coming in correctly.
Update callback comes with updated document - print that to know what happens.
The $ is referring only the first item in the array. If you want to update all you have to use find and save:
UserProfile.findOne({
'Notifications._id' : req.body.NotificationID
}, function(err, doc) {
_.find(doc.Notifications, {_id: req.body.NotificationID}).Status = 1;
doc.save(function (err) {
if (err)
res.send(err);
})
})

How to access JSON element which has "-" character in the name in JavaScript

I have a JSON object which returns following values.
{
"articles":[
{
"paper-id":"id",
"paper-id-type":"type",
"title":"title",
"url":"url",
"abstract":"abs",
"date":"date",
"publication-forum":"forum",
"publication-forum-type":"type",
"authors":"auth",
"keywords":"key1,key2"
}
}
I tried to access these results through JavaScript.
First I created an array and assigned these results to the array.
The content of the array (named articles) object looks like this;
abstract: "xxx"
authors: "yyy"
date: "1111"
keywords: "key1, key2"
paper-id: "abc"
paper-id-type: "xxx"
publication-forum: "yyy"
publication-forum-type: "zzz"
title: "www"
url: "url"
Then I tried to access each value in these elements using the format,
articles[0]["abstract"]
It works for elements that do not have "-" character. So when I tried to extract the paper-id;
articles[0]["paper-id"]
I'm getting the error [Exception: SyntaxError: Unexpected token []
Does anyone know how to solve this problem ?
The problem is because you forgot to close the [] and the {} in your JSON
You JSON should look like this
{
"articles":[
{
"paper-id":"id",
"paper-id-type":"type",
"title":"title",
"url":"url",
"abstract":"abs",
"date":"date",
"publication-forum":"forum",
"publication-forum-type":"type",
"authors":"auth",
"keywords":"key1,key2"
}]
}
abc = {
"articles": [{
"paper-id": "id",
"paper-id-type": "type",
"title": "title",
"url": "url",
"abstract": "abs",
"date": "date",
"publication-forum": "forum",
"publication-forum-type": "type",
"authors": "auth",
"keywords": "key1,key2"
}
]
};
for (i in abc['articles'][0]) {
console.log(abc['articles'][0][i]);
}

Categories