I have this document saved in my mongo collection called exam
// meteor:PRIMARY> db.exam.find()
{
"_id" : "RLvWTcsrbRXJeTqdB",
"examschoolid" : "5FF2JRddZdtTHuwkx",
"examsubjects" : [
{
"subject" : "Z4eLrwGwqG4pw4HKX"
},
{
"subject" : "fFcWby8ArpboizcT9"
}
],
"examay" : "NrsP4srFGfkc5cJkz",
"examterm" : "5A5dNTgAkdRr5j53j",
"examclass" : "gYF2wE4wBCRy9a3ZC",
"examname" : "First",
"examdate" : ISODate("2016-05-07T22:41:00Z"),
"examresultsstatus" : "notreleased"
}
I am trying to select data from this document and saving it into another using this code.The aim is to have the examsubjects value in the document above to be the key in the document i am inserting into.
'click .reactive-table tr': function() {
Session.set('selectedPersonId', this._id);
var cursor = Exam.find({ _id:
Session.get("selectedPersonId")}).fetch();
cursor.forEach(function(doc){
for (i = 0; i < doc.examsubjects.length; i++) {
for (var prop in doc.examsubjects[i]) {
console.log("obj." + prop + " = " + doc.examsubjects[i][prop]);
var subj = doc.examsubjects[i][prop];
Told.insert({
examschoolid:"sms",
examname:doc.examname,
examsubjects: [{subj : "0"}],
examay:doc.examay,
examterm:doc.examterm,
examclass:doc.examclass,
examdate:doc.examdate
});
}
}
});
},
When the code runs,the variable subj that holds the subjects value just inserts subj not knowing its a variable like this
{
"_id" : "5yjwFanBAupgu9GHq",
"examschoolid" : "sms",
"examname" : "First",
"examsubjects" : [
{
"subj" : "0"
}
],
"examay" : "NrsP4srFGfkc5cJkz",
"examterm" : "5A5dNTgAkdRr5j53j",
"examclass" : "gYF2wE4wBCRy9a3ZC",
"examdate" : ISODate("2016-05-07T22:41:00Z")
}
Why is the variable not being seen as a variable?.
Edit
'click .reactive-table tr': function() {
Session.set('selectedPersonId', this._id);
var cursor = Exam.find({ _id: Session.get("selectedPersonId")}).fetch();
cursor.forEach(function(doc){
var sq = function(){
for (i = 0; i < doc.examsubjects.length; i++) {
for (var prop in doc.examsubjects[i]) {
const subj = doc.examsubjects[i][prop];
let subject = {};
subject[subj] = "0";
return [subject];
}
}
}
console.log(sq());
Told.insert({
examschoolid:"sms",
examname:doc.examname,
examsubjects: sq(),
examay:doc.examay,
examterm:doc.examterm,
examclass:doc.examclass,
examdate:doc.examdate
});
});
//Uncaught TypeError: cursor.count is not a function
},
The updated code almost works,but only inserts 1 record.
That's how JSON works, it takes keys literally. Fix it by using ES6 brackets notation:
examsubjects: [{
[subj] : "0"
}],
This is because it is treated as a key in a literal object.
If you want to have subj's value as your key, you will need to use the bracket notation, creating the object beforehand:
const subj = doc.examsubjects[i][prop];
let subject = {};
subject[subj] = "0";
Told.insert({
examschoolid:"sms",
examname:doc.examname,
examsubjects: [subject],
...
});
Related
var user_business_data =[
{
"user_id":"5db3e3b1",
"blog":{
"blog_id":"128c522e"
},
"business_units":[
{
"business_unit_id":"000396c9",
"viewing":101
},
{
"business_unit_id":"01821e44",
"viewing":102
},
{
"business_unit_id":"02cbcad5",
"viewing":103
}
]
}
]
I want to get all the "business_unit_id" and store in a varible. for this i need get all the "business_unit_id". so i tried to print all the id's with the below code but i was unable to print.
if (undefined !== user_business_data.business_units && user_business_data.business_units.length) {
for(var i=0;i<user_business_data.business_units.length;i++){
var key = user_business_data.business_units[i];
console.log("Key : "+key, "Values : "+user_business_data.business_units[key]);
}
} else {
console.log("Undefined value");
}
There always i am getting undefined value.
var user_business_data=[{"user_id":"5db3e3b1","blog":{"blog_id":"128c522e"},"business_units":[{"business_unit_id":"000396c9","viewing":101},{"business_unit_id":"01821e44","viewing":102},{"business_unit_id":"02cbcad5","viewing":103}]}]
var unit_ids = [];
user_business_data.forEach(function(user) {
user.business_units.forEach(function(business) {
unit_ids.push(business.business_unit_id);
});
});
console.log(unit_ids);
user_business_data is an array, not an object, so you either need to loop through it or read a specific index from it.
Also, key in your code will be an object (a single business unit object), so you can't print it directly - instead you need to fetch a specific property within the object.
Here's a simple demo reading the first key from the outer array and then listing all the specific properties from the business units. The code can be simplified further potentially, but this illustrates the point:
var user_business_data =
[{
"user_id": "5db3e3b1",
"blog": {
"blog_id": "128c522e"
},
"business_units": [{
"business_unit_id": "000396c9",
"viewing": 101
},
{
"business_unit_id": "01821e44",
"viewing": 102
},
{
"business_unit_id": "02cbcad5",
"viewing": 103
}
]
}]
if (undefined !== user_business_data[0].business_units && user_business_data[0].business_units.length) {
for (var i = 0; i < user_business_data[0].business_units.length; i++) {
var key = user_business_data[0].business_units[i].business_unit_id;
console.log("Key : " + key, "Values : " + user_business_data[0].business_units[i].viewing);
}
} else {
console.log("Undefined value");
}
I suggest you get clear in your head the difference between arrays, objects and properties in JSON / JS objects, and then this kind of thing will become trivial.
user_business_data is an array and not an object.If you want to access any object from an array you have to specify the index as of which position you are referring.Therefore in your example change it to following to work:
if (undefined !== user_business_data[0].business_units && user_business_data[0].business_units.length) {
for(var i=0;i<user_business_data[0].business_units.length;i++){
var key = user_business_data[0].business_units[i]. business_unit_id;
console.log("Key : "+key, "Values : "+user_business_data[0].business_units[key]);
}
} else {
console.log("Undefined value");
}
It's because user_business_data is an array, not an object yet you access it like user_business_data.business_units instead of user_business_data[0].business_units
var user_business_data = [{"user_id": "5db3e3b1","blog": {"blog_id": "128c522e"}, "business_units": [{"business_unit_id": "000396c9","viewing": 101}, {"business_unit_id": "01821e44","viewing": 102},{"business_unit_id": "02cbcad5","viewing": 103}]}];
// Both methods give the same result, but the second checks for null values.
var ids1 = user_business_data[0].business_units.map(x => x.business_unit_id)
console.log('Method 1:', ids1);
// The && check for null values, kinda like an if statement.
var data = user_business_data.length && user_business_data[0]
var units = data && data.business_units
var ids2 = units && units.length && units.map(x => x.business_unit_id)
console.log('Method 2:', ids2)
If you want to print only the business_unit_ids then you can do as follows:
var user_business_data =
[
{
"user_id": "5db3e3b1",
"blog": {
"blog_id": "128c522e"
},
"business_units": [
{
"business_unit_id": "000396c9",
"viewing": 101
},
{
"business_unit_id": "01821e44",
"viewing": 102
},
{
"business_unit_id": "02cbcad5",
"viewing": 103
}
]
}
]
for(var i=0;i<user_business_data[0]["business_units"].length;i++){
console.log(user_business_data[0]["business_units"][i].business_unit_id)
}
I'm struggling on adding an Object to an Array (E-commerce context).
My "tc_vars" datalayer is mapped with another datalayer which is called "wa_data". The latter sends the requested information to the first one.
An Object in that case will be a specific product and the Array will be the cart.content property :
var tc_vars = {
nav : {
siteCategory : wa_data.nav.siteCategory,
environment :wa_data.nav.environment,
siteType :wa_data.nav.siteType,
siteName :wa_data.nav.siteName,
pageName :wa_data.nav.pageName,
siteSection :wa_data.nav.siteSection,
country :wa_data.nav.country,
language :wa_data.nav.language,
template :wa_data.nav.template,
doNotTrack :window.navigator.doNotTrack,
customReferrer :wa_data.nav.customReferrer,
genomeID :wa_data.nav.genomeID,
mdmBID :wa_data.nav.mdmBID,
mdmIID :wa_data.nav.mdmIID
},
profile : {
uplayID : readCookie("user_id"),
loginStatus : ''
},
internalSearch : {
searchStatus :wa_data.internalSearch.searchStatus,
searchFilters :wa_data.internalSearch.searchFilters,
searchKeyWord :wa_data.internalSearch.searchKeyWord,
totalResults :wa_data.internalSearch.totalResults,
resultPosition :wa_data.internalSearch.resultPosition,
autoCompletion :wa_data.internalSearch.autoCompletion
},
product : {
productID :wa_data.product.productID,
unitSalePrice :wa_data.product.unitSalePrice,
salePrice :wa_data.product.salePrice,
stockAvailability :wa_data.product.stockAvailability,
salesType :wa_data.product.salesType,
costOfGood :wa_data.product.costOfGood
},
cart : {
orderID:wa_data.cart.orderID,
cartOpen:wa_data.cart.cartOpen,
cartAdd:wa_data.cart.cartAdd,
cartRemove:wa_data.cart.cartRemove,
cartView:wa_data.cart.cartView,
checkout:wa_data.cart.checkout,
purchase:wa_data.cart.purchase,
currency:wa_data.cart.currency,
paymentMethod:wa_data.cart.paymentMethod,
orderShipping:wa_data.cart.orderShipping,
orderTotalAmountDiscounted:wa_data.cart.orderTotalAmountDiscounted,
orderTotalAmountNotDiscounted:wa_data.cart.orderTotalAmountNotDiscounted,
orderTaxAmount:wa_data.cart.orderTaxAmount,
orderDiscountedAmount:wa_data.cart.orderDiscountedAmount,
orderShippingCost:wa_data.cart.orderShippingCost,
billingRegion:wa_data.cart.billingRegion,
billingCity:wa_data.cart.billingCity,
orderStatus:wa_data.cart.orderStatus,
content : [{
productID:'',
name:'',
quantity :'',
promoCode:'',
offerID:'',
salesType:'',
platform :'',
unitSalePrice:'',
salePrice:'',
stockAvailability:'',
lineItemTotalAmountDiscounted:'',
lineItemTotalAmountNotDiscounted:'',
lineItemTaxAmount:'',
lineItemDiscountedAmount:'',
lineItemShippingCost:'',
crossSell:'',
upSell:''
}]
},
tech : {
containerVersion : wa_data.tech.containerVersion
}
}
//Scanning for the content using a loop
if (typeof tc_vars.cart.content !== 'undefined' && tc_vars.nav.pageName === 'Basket'){
for(i=0; i < tc_vars.cart.content.length; i++) {
tc_vars.cart.content[i].productID = wa_data.cart.content[i].productID;
tc_vars.cart.content[i].name = wa_data.cart.content[i].name;
tc_vars.cart.content[i].quantity = wa_data.cart.content[i].quantity;
tc_vars.cart.content[i].promoCode = wa_data.cart.content[i].promoCode;
tc_vars.cart.content[i].offerID = wa_data.cart.content[i].offerID;
tc_vars.cart.content[i].salesType = wa_data.cart.content[i].salesType;
tc_vars.cart.content[i].platform = wa_data.cart.content[i].platform;
tc_vars.cart.content[i].unitSalePrice = wa_data.cart.content[i].unitSalePrice;
tc_vars.cart.content[i].salePrice = wa_data.cart.content[i].salePrice;
tc_vars.cart.content[i].stockAvailability = wa_data.cart.content[i].stockAvailability;
tc_vars.cart.content[i].lineItemTotalAmountDiscounted = wa_data.cart.content[i].lineItemTotalAmountDiscounted;
tc_vars.cart.content[i].lineItemTotalAmountNotDiscounted = wa_data.cart.content[i].lineItemTotalAmountNotDiscounted;
tc_vars.cart.content[i].lineItemTaxAmount = wa_data.cart.content[i].lineItemTaxAmount;
tc_vars.cart.content[i].lineItemDiscountedAmount = wa_data.cart.content[i].lineItemDiscountedAmount;
tc_vars.cart.content[i].lineItemShippingCost = wa_data.cart.content[i].lineItemShippingCost;
tc_vars.cart.content[i].crossSell = wa_data.cart.content[i].crossSell;
tc_vars.cart.content[i].upSell = wa_data.cart.content[i].upSell;
}
}
The problem I'm facing here is that my code is not creating a new object for each new product that is added to the cart content (with all the dedicated properties of the new object).
I've tried using a loop which scans my cart content Array but apparently it's not working (not adding a new object inside the Array). Seems like I'm missing something.
Do you guys have any ideas?
Thx a lot
J
tc_vars.cart.content[i] is undefined. You need to define it first, before filling it up.
for(i=0; i < tc_vars.cart.content.length; i++) {
tc_vars.cart.content[i] = {}; // Creates an empty object
tc_vars.cart.content[i].productID = wa_data.cart.content[i].productID; // Starts filling it
// ....
}
As an alternative (lighter syntax and faster execution), you could also write :
for(i=0; i < tc_vars.cart.content.length; i++) {
tc_vars.cart.content[i] = {
productID : wa_data.cart.content[i].productID,
name : wa_data.cart.content[i].name,
// ....
}
}
But we don't usually add things to an Array by its index. We just push things into it :
for(i=0; i < tc_vars.cart.content.length; i++) {
tc_vars.cart.content.push({
productID : wa_data.cart.content[i].productID,
name : wa_data.cart.content[i].name,
// ....
});
}
This being said, it looks like all you're doing here is copying (not instanciating) wa_data.cart.content into tc_vars.cart.content. So you can completely forget my answer and replace your whole for loop with Gurvinder's answer (+1'd him):
tc_vars.cart.content = JSON.parse(JSON.stringify(wa_data.cart.content));
Unless wa_data already have objects repeated at all the index, following code should work
tc_vars.cart.content = JSON.parse(JSON.stringify(wa_data.cart.content));
You can use an object literal:
tc_vars.cart.content[i] = {
productID: wa_data.cart.content[i].productID,
name: wa_data.cart.content[i].name,
quantity: wa_data.cart.content[i].quantity,
promoCode: wa_data.cart.content[i].promoCode,
offerID: wa_data.cart.content[i].offerID,
salesType: wa_data.cart.content[i].salesType,
platform: wa_data.cart.content[i].platform,
unitSalePrice: wa_data.cart.content[i].unitSalePrice,
salePrice: wa_data.cart.content[i].salePrice,
stockAvailability: wa_data.cart.content[i].stockAvailability,
lineItemTotalAmountDiscounted: wa_data.cart.content[i].lineItemTotalAmountDiscounted,
lineItemTotalAmountNotDiscounted: wa_data.cart.content[i].lineItemTotalAmountNotDiscounted,
lineItemTaxAmount: wa_data.cart.content[i].lineItemTaxAmount,
lineItemDiscountedAmount: wa_data.cart.content[i].lineItemDiscountedAmount,
lineItemShippingCost: wa_data.cart.content[i].lineItemShippingCost,
crossSell: wa_data.cart.content[i].crossSell,
upSell: wa_data.cart.content[i].upSell
}
I am having following document in the mongoDB. I want to change the currentVisit data type to integer
{
"_id" : ObjectId("5385e14f5caf98cc0712931c"),
"location" : {
"language" : null,
"country" : "null",
},
"request" : [
{
"currentVisit" : "1401292066",
"lastVisit" : "1401292066",
"visitedTime" : "1401282894"
}
]
}
Note
I had tried the following but it is not working.
db.visits.find().forEach( function (x) { x.request.currentVisit = parseInt(x.request.currentVisit); db.visits.save(x);});
Any suggestion will be grateful
You were close but you need to loop the inner array as well
db.visits.find().forEach(function (x) {
for ( var i=0; i <= x.request.length; i++ ) {
x.request[i].currentVisit = parseInt(x.request[i].currentVisit);
}
db.visits.save(x);
});
You probably want all of them really:
db.visits.find().forEach(function (x) {
for ( var i=0; i <= x.request.length; i++ ) {
x.request[i].currentVisit = parseInt(x.request[i].currentVisit);
x.request[i].lastVisit = parseInt(x.request[i].lastVisit);
x.request[i].visitedTime = parseInt(x.request[i].visitedTime);
}
db.visits.save(x);
});
Your request field is an array, so you should iterate over it to change the value "currentVisit" field in each subdocument:
db.visits.find().forEach( function (doc) {
doc.request.forEach(function(subdoc) {
subdoc.currentVisit = parseInt(subdoc.currentVisit);
});
db.visits.save(doc);
});
data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
how to format the above array into this
var name = {
"user": {
"name" : [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
}
}
I tried var name['name'] = data and don't know how to wrap the result. I want to wrap the result with 'user' as it assoc.
You can't assign properties as you create the object. Either first create the object and then set the property:
var name = {};
name.user = { name : data };
or create the entire object at once:
var name = { user: { name: data } };
var data = [{'name':'John'},
{'name':'Smith'},
{'name':'James'}]
var name = {
"user": {
"name" : data
}
}
I try to dynamically generate a listview in jQuery. This works perfectly for the whole list, but now I need to filter/search/reduce my initial data:
var rezepte = [
{ "name" : "Eierkopf" , "zutaten" : ["Eier", "Zucker"] , "zubereitung" : "alles schön mischen." },
{ "name" : "Käseschnitte" , "zutaten" : ["Käse", "Brot", "Paprika"] , "zubereitung" : "Käse drauf und in den Ofen" },
{ "nme" : "Gemüse-Auflauf" , "zutaten" : ["Lauch"] , "zubereitung" : "1. schneiden 2. Kochen 3. essen" }
];
I would like to filter/search "recipe" by a searcharray like var searcharray = ["Zucker", "Paprika"] resulting in:
var result = [
{ "name" : "Eierkopf" , "zutaten" : ["Eier", "Zucker"] , "zubereitung" : "alles schön mischen." },
{ "name" : "Käseschnitte" , "Zutaten" : ["Käse", "Brot", "Paprika"] , "zubereitung" : "Käse drauf und in den Ofen" }];
I have tried a lot of things within the for loop: filter, map, push - but all without sucess always resuling in undefined objects.
I am also not sure what syntax my recipe Array should be: there must be the possibility of variable amount of "ingredients".
Any help and hint would be most appreciated.
Thanks a lot,
Andi
Using native Array functions, this should work:
result = recipes.filter(function(recipe) {
return search.any(function(ingredient) {
return recipe.ingredients.indexOf(ingredient) != -1;
});
});
Using jQuery, it would be
result = $.grep(recipes, function(recipe) {
for (var i=0; i<search.length; i++)
if ($.inArray(recipe.ingredients, search[i]) != -1)
return true;
return false;
});
var rezepte = [
{ "name" : "Eierkopf" , "zutaten" : ["Eier", "Zucker"] , "zubereitung" : "alles schön mischen." },
{ "name" : "Käseschnitte" , "zutaten" : ["Käse", "Brot", "Paprika"] , "zubereitung" : "Käse drauf und in den Ofen" },
{ "nme" : "Gemüse-Auflauf" , "zutaten" : ["Lauch"] , "zubereitung" : "1. schneiden 2. Kochen 3. essen" }
];
function search() {
var search = $("#searchfield").val(); // returns string
var searcharray = search.split(',');
if (searcharray == "") {
check = $.isArray(searcharray);
alert(check); // true
return rezepte;
} else {
var result = [];
alert("till here fine");
result = $.grep(rezepte, function(rezept) {
for (var i=0; i<searcharray.length; i++) {
if ($.inArray(searcharray[i], rezept.zutaten) != -1)
return true;
}
return false;
});
}
console.log(result);
return result;
}
$(function(){
$("#search").click(search);
})
I have it working with this code. See demo: http://jsfiddle.net/VcZtE/1/ (results could be seen in browser console). The only difference from your code is here: if ($.inArray(searcharray[i], rezept.zutaten) != -1). According to docs for inArray needle should be a first parameter and array to search in - second. And you have it in opposite way: array is passed as a first param and needle (value to search for) as a second.