I'm updating the update_payment_summary function in the Point_Of_Sale, this function is part of the PaymentScreenWidget.
Now I'd like to retrieve the products from the orderlines.
I tried with
var order = this.pos.get('selectedOrder');
var orderlines = order.get('orderLines').models;
But when I print orderlines I get [object Object]
Any ideas how I can get the product object of every orderline?
Yes there is a reason why it shows object.
OrderlineCollection definition.
module.OrderlineCollection = Backbone.Collection.extend({
model: module.Orderline,
});
Orderline definition in Order Model.
orderLines: new module.OrderlineCollection()
So if you observe above code it shows that orderline is an object of OrderlineCollection model and while you get orderlines from order model it will gives you an object of OrderlineCollection.
In order to identify what's there inside object you can iterate through it or you may print key-value from that object.
alert(orderline.forEach(function(k,v){k + " => + v}));
Or you can loop through the orderlines.
for (line in orderline){
alert(line.product_id);
}
use the get_orderlines() function to get OrderLines from particular Order.
var order = this.pos.get_order();
var products = _.map(order.get_orderlines(), function (line) {return line.product; });
console.log(products);
here i user Underscore.js for create a list of products.
you can iterate loop with products list like,
for(var i =0; i < products.length; i++)
console.log(products[i].id);
Related
I'm developing a system for manage directors in group of companies. I need to filter directors for companies as assigned. After I pass data from controller to view, when selecting companies the filter shows incorrect results.
The above results will show when I console.log(this.directorships) those. I think it's because for single data it'll show as an array. But if those multiple it'll show as objects.
I'm looping those inside for loop as follows to print results.
for (let i = 0; i < this.directorships.length; i++) {
single_director = this.directorships[i].director_profile;
finalArray.push(single_director);
}
MyController.php
public function activeBoard($company_id){
$directorship = Directorship::with(['director_profile'])
->where('master_data_id',$company_id)
->get();
$active_directors = $directorship->where('active',1);
return $active_directors;
}
Can anyone please tell me what's the mistake I have done here? Or are there any methods to do what I expect?
It's hard to tell from the screenshots, but Objects in JavaScript are not iterable using a standard for loop, and don't have a length property by default. You should first check whether the directorships is an array, and then iterate or read suitably. For example:
let directorships_is_array = Array.isArray(directorships);
if(directorships_is_array) {
// ... loop through array
}
else {
// ... perform other function on object
}
There are a number of ways to iterate through an object, and get an objects length. The new for in loops can iterate through an object. For example:
for(let director in directorships) {
console.log(director);
}
You can also get the length of the Object using something like, let directors_length = Object.keys(directorships).length and then do something like this:
let number_of_directorships = Object.keys(directorships).length;
for(let i=0; i<number_of_directorships; i++) {
// ... iterate here
}
you need to use query like this you have initialize query before the condition
public function activeBoard($company_id){
$directorship = Directorship::where('master_data_id',$company_id)->where('active',1)->with('director_profile')->get();
return $directorship;
}
I'm currently facing a difficulty in my codes.
First i have an array of objects like this [{Id:1, Name:"AML", allowedToView:"1,2"}, {Id:2, Name:"Res", allowedToView:"1"}...] which came from my service
I assign it in variable $scope.listofResource
Then inside of one of my objects I have that allowedToView key which is a collection of Id's of users that I separate by comma.
Then I have this code...
Javascript
$scope.listofResource = msg.data
for (var i = 0; i < msg.data.length; i++) {
First I run a for loop so I can separate the Id's of every user in allowedToView key
var allowed = msg.data[i].allowedToView.split(",");
var x = [];
Then I create a variable x so I can push a new object to it with a keys of allowedId that basically the Id of the users and resId which is the Id of the resource
for (var a = 0; a < allowed.length; a++) {
x.push({ allowedId: allowed[a], resId: msg.data[i].Id });
}
Then I put it in Promise.all because I have to get the Name of that "allowed users" base on their Id's using a service
Promise.all(x.map(function (prop) {
var d = {
allowedId: parseInt(prop.allowedId)
}
return ResourceService.getAllowedUsers(d).then(function (msg1) {
msg1.data[0].resId = prop.resId;
Here it returns the Id and Name of the allowed user. I have to insert the resId so it can pass to the return object and it will be displayed in .then() below
return msg1.data[0]
});
})).then(function (result) {
I got the result that I want but here is now my problem
angular.forEach(result, function (val) {
angular.forEach($scope.listofResource, function (vv) {
vv.allowedToView1 = [];
if (val.resId === vv.Id) {
vv.allowedToView1.push(val);
I want to update $scope.listofResource.allowedToView1 which should hold an array of objects and it is basically the info of the allowed users. But whenever I push a value here vv.allowedToView1.push(val); It always updates the last object of the array.
}
})
})
});
}
So the result of my code is always like this
[{Id:1, Name:"AML", allowedToView:"1,2", allowedToView:[]}, {Id:2, Name:"Res", allowedToView:"1", allowedToView:[{Id:1, Name:" John Doe"}]}...]
The first result is always blank. Can anyone help me?
Here is the plunker of it... Plunkr
Link to the solution - Plunkr
for (var i = 0; i < msg.length; i++) {
var allowed = msg[i].allowedToView.split(",");
msg[i].allowedToView1 = [];
var x = [];
Like Aleksey Solovey correctly pointed out, the initialization of the allowedToView1 array is happening at the wrong place. It should be shifted to a place where it is called once for the msg. I've shifted it to after allowedToView.split in the first loop as that seemed a appropriate location to initialize it.
I am new to VueJs and working on a small nutrition app. Currently, we want to make food recs based on certain nutrients.
The JS is as follows:
recommendFood: function() {
this.recs = {};
var _this = this;
var getItem = function(ndbno,i,nid) {
_this.$http.get('http://127.0.0.1:3000/item?ndbno=' + ndbno).then(function(response) {
var someData = response.body;
var nutrients = someData.report.food.nutrients;
var item = someData.report.food;
item = this.addNutrientsToItem(item, nutrients);
this.recs[nid].push(item);
});
};
for (var i=0; i<this.low_nutrients.length; i++) {
this.low_nutrients[i].recs = [];
this.recs[this.low_nutrients[i].id] = [];
for (var k=0; k<this.low_nutrients[i].food_map.length; k++) {
var ndbno = this.low_nutrients[i].food_map[k];
getItem(ndbno,i,this.low_nutrients[i].id);
}
}
console.log(this.recs)
}
I want this.recs to be an object with attributes that are equivalent to a nutrient id (that we store). Each nutrient has a food_map array attached to the object that contains id's of foods that would be the recommendations. I need to send those id's (ndbno) to the http request to receive the object of that food recommendation (item).
The this.recs object actually populates correctly (despite there probably being a better way to write my code), however since it's waiting on the loop and promise, the html renders before the object is complete. Therefore, my html is blank. How can I display the recs on the html once they are updated on the promise result?
Here is my HTML:
<div v-for="(nutrient, idx) in low_nutrients">
<h2>{{nutrient.name}}</h2>
<div>Recommended Foods:</div>
<div>
<div>Recs:</div>
<div v-for="rec in recs[nutrient.id]">{{rec}}</div>
</div>
</div>
The desired object this.recs should look something like this (and it does show this in the console):
this.recs = {
291: [{},{},{}],
316: [{},{},{}]
}
The problem is that this.recs starts out empty. Vue cannot detect property additions, so you have to use set to tell it that new properties have been added (and to make those properties reactive).
Or you can re-assign a new object to this.recs rather than modifying its contents.
I'm wondering how to store the response from a Facebook API call into a Javascript array.
This is the call I'm making:
FB.api('/MYAPPID/scores/?fields=user', function(response) {
for (var i = 0; i < response.data.length; i++){
var grabbedarray = response.data[i].user.id;
console.log(grabbedarray);
}
})
The call FB.api('/MYAPPID/scores/?fields=user' returns a data set that has "name" and "id" properties for each element in the array, but I'm only interested in storing the "id" parts of the array.
The above code iterates through the response from the call, it checks user.id in each row of the array, and then the console.log shows the id for that row. This means that var grabbedarray is appearing several times in the console, showing a different id each time. I understand why this is happening, but I'm trying to get all the ids stored into one array, and then I'd like to console.log that.
So the final result in the console should be something like:
[456345624, 256456345, 253456435727, 376573835, 2652453245]
I've tried changing the call to FB.api('/MYAPPID/scores/?fields=user.id' in the hope that the response will show only a list of ids, but it's not working.
Does anyone have any idea how to solve this problem?
Thank you in advance!
To keep the approach you were using, you can push each new id you find into an array you define outside of the for loop.
var idArray = [];
FB.api('/MYAPPID/scores/?fields=user', function(response) {
for (var i = 0; i < response.data.length; i++){
idArray.push(response.data[i].user.id);
}
console.log(idArray);
})
You could also use map to transform the response array into what you want.
var idArray = [];
FB.api('/MYAPPID/scores/?fields=user', function(response) {
idArray = response.data.map(function(x){ return x.user.id });
console.log(idArray);
})
I am pretty new to the 'game' and was wondering if it's possible to order newly added data (through a form and inputs) to the Firebase numerically so each new data entry gets the ID (number of the last added data +1).
To make it more clear, underneath you can find a screenshot of how data is currently being added right now. The datapoint 0-7 are existing (JSON imported data) and the ones with the randomly created ID belong to new entries. I would like to have the entries to comply to the numbering inside of my Firebase, because otherwise my D3 bar chart won't be visualised.
var firebaseData = new Firebase("https://assignment5.firebaseio.com");
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.push().set({games: gameName, medals: medalCount, summergames: bool});
evt.preventDefault();
}
var submit = document.getElementsByTagName('button')[0];
submit.onclick = funct1;
UPDATE:
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
for (var i = 0; i < 10; i++)
{
firebaseData.child('7' + i).set({games: gameName, medals: medalCount, summergames: bool}(i)); };
Problem:
There are two ways to generate ids for your document nodes.
Calling .push() on your reference will generate that unique id.
Calling .set() on your reference will allow you to use your own
id.
Right now you're using .push().set({}), so push will generate an new id and the set will simply set the data.
// These two methods are equivalent
listRef.push().set({user_id: 'wilma', text: 'Hello'});
listRef.push({user_id: 'wilma', text: 'Hello'});
Using .set() without .push() will allow you to control your own id.
Using .push():
When managing lists of data in Firebase, it's important to use unique generated IDs since the data is updating in real time. If integer ids are being used data can be easily overwritten.
Just because you have an unique id, doesn't mean you can't query through your data by your ids. You can loop through a parent reference and get all of the child references as well.
var listRef = new Firebase('https://YOUR-FIREBASE.firebaseio.com/items');
// constructor for item
function Item(id) {
this.id = id;
};
// add the items to firebase
for (var i = 0; i < 10; i++) {
listRef.push(new Item(i));
};
// This will generate the following structure
// - items
// - LGAJlkejagae
// - id: 0
// now we can loop through all of the items
listRef.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var name = childSnapshot.name();
var childData = childSnapshot.val();
console.log(name); // unique id
console.log(childData); // actual data
console.log(childData.id); // this is the id you're looking for
});
});
Within the childData variable you can access your data such as the id you want.
Using .set()
If you want to manage your own ids you can use set, but you need to change the child reference as you add items.
for (var i = 0; i < 10; i++) {
// Now this will create an item with the id number
// ex: https://YOUR-FIREBASE.firebaseio.com/items/1
listRef.child('/' + i).set(new Item(i));
};
// The above loop with create the following structure.
// - items
// - 0
// - id: 0
To get the data you can use the same method above to loop through all of the child items in the node.
So which one to use?
Use .push() when you don't want your data to be easily overwritten.
Use .set() when your id is really, really important to you and you don't care about your data being easily overwritten.
EDIT
The problem you're having is that you need to know the total amount of items in the list. This feature is not implemented in Firebase so you'll need to load the data and grab the number of items. I'd recommend doing this when the page loads and caching that count if you really desire to maintain that id structure. This will cause performance issues.
However, if you know what you need to index off of, or don't care to overwrite your index I wouldn't load the data from firebase.
In your case your code would look something like this:
// this variable will store all your data, try to not put it in global scope
var firebaseData = new Firebase('your-firebase-url/data');
var allData = null;
// if you don't need to load the data then just use this variable to increment
var allDataCount = 0;
// be wary since this is an async call, it may not be available for your
// function below. Look into using a deferred instead.
firebaseData.once('value', function(snapshot) {
allData = snapshot.val();
allDataCount = snapshot.numChildren(); // this is the index to increment off of
});
// assuming this is some click event that adds the data it should
function funct1(evt) {
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.child('/' + allDataCount).set({
games: gameName,
medals: medalCount,
summergames: bool
});
allDataCount += 1; // increment since we still don't have the reference
};
For more information about managing lists in Firebase, there's a good article in the Firebase API Docs. https://www.firebase.com/docs/managing-lists.html