KnockoutJS Accessing an array of objects in a separate class - arrays

So i have 2 classes, users and health readings. i made a array of user objects with an array of readings inside it.i just want access to the date and weight in the reading array, i have been trying for a long time to figure this out! please help this simple problem is driving me nuts!
// Class to represent a row in the seat reservations grid
function Reading(theDate,theWeight)
{
self.theDate=ko.observable(theDate);
self.theWeight=ko.observable(theWeight);
}
function User(name,weight,date) {
var self = this;
self.name = name;
self.date = date;
self.weight = ko.observable(weight);
self.theReadings = ko.observableArray([
new Reading(12,13)
]);
}
// Editable data
self.users = ko.observableArray([
new User("George",1,2012),
new User("Bindu",2,2012)
]);
/this alerts an object but i dont know how to access the weight/date variable
alert(self.users()[0].theReadings()[0]);
self.readings = ko.observableArray([
new Reading(12,13)

Just missed a few things on this one.
Here ya go.
http://jsfiddle.net/EN7y4/3/
Namely. You had "self.theWeight" in function Reading instead of "this."...
Happy Coding!

alert(self.users()[0].theReadings()[0].theWeight();
I would recommend removing the 'thes'. That's an uncommon style.

Related

Remove random item from array and push to new array

Thank you in advance! I'm new to coding and learning how to deal with Arrays. I am trying to remove random items from an array (deck of cards), and populate a new array (called hand). The problem I always seem to have with arrays is taking the results of one and creating a new function/array/ etc.. Currently, I am outputting 2 separate arrays and I can't seem to push them into one.
let deck = ["dA","dQ","dK","dJ","d10","d09","d08",
"d07","d06","d05","d04","d03","d02","hA","hQ","hK",
"hJ","h10","h09","h08","h07","h06","h05","h04","h03"];
var hand = deck.splice(Math.floor(Math.random()*deck.length),1);
console.log(hand)
var hand = deck.splice(Math.floor(Math.random()*deck.length),1);
console.log(hand);
In your code, just you need to push the value returned from splice method rather than directly assigning it.
By this way every time a new value that gets deleted and will be added to the new array called hand. Hope this helps. :-)
let deck = ["dA","dQ","dK","dJ","d10","d09","d08",
"d07","d06","d05","d04","d03","d02","hA","hQ","hK",
"hJ","h10","h09","h08","h07","h06","h05","h04","h03"];
var hand = [];
const getSelectedCard = () => deck.splice(Math.floor(Math.random()*deck.length),1)
let selectedCard = getSelectedCard();
hand.push(...selectedCard) //or hand.push(selectedCard[0])
console.log(hand);
selectedCard = getSelectedCard();
hand.push(...selectedCard)
console.log(hand);

Google Earth Engine: set Feature to FeatureCollection, but not a whole Array

I try to add a new Feature to the large Feature Collection, but with a function set() its override the whole list to each feature. But my purpose is to add each value from the array to the corresponding FeatureCollection. Can anybody help me?
var table = ee.FeatureCollection(ft:.....blablabla);
**//Create an Array from the property DN in the FeatureCollection:**
var propert = table.limit(100).aggregate_array('DN');
*// Values less than 1 will be set to 1, larger than 1== 0:*
var limit = ee.Array(propert).lt(1);
print(limit);
//Function, that add the list! of features (limit) to new property (Class) in the FeatureCollection ("table").
var addFeature = function(ar) {
return ar.set({Class: limit});
//Map throw the Featurecollection table
var areaAdded = table.limit(100).map(addArea);
};
So, if you can see, my code add the whole Array [limit] to each property in the FeatureCollection, not a first Value from the Array to the first property and so on...
Could anybody help me? thank you
If you have a smallish number of features, you can convert the feature collection to a list, convert the array to a list, zip() them together, map a function over the lists to set the property. Toy example:
var features = [
ee.Feature(ee.Geometry.Rectangle(30.01, 59.80, 30.59, 60.15), {name: 'Voronoi'}),
ee.Feature(ee.Geometry.Point(-73.96, 40.781), {name: 'Thiessen'}),
ee.Feature(ee.Geometry.Point(6.4806, 50.8012), {name: 'Dirichlet'})
];
var fromList = ee.FeatureCollection(features);
var array = ee.Array([2, 3, 5]);
var lists = fromList.toList(fromList.size()).zip(array.toList());
var features = ee.FeatureCollection(lists.map(function(l) {
return ee.Feature(ee.List(l).get(0)).set('foo', ee.List(l).get(1));
}));
print(features);

Randomly select an instantiation of a class and display it?

Goal: Randomly select a member of a class containing people, and display the information in an alert.
Here is what I am doing: I have a class called Entrepreneurs. Inside the class are variables for name, networth etc. I have instantiated the class with several Entrepreneurs as follows:
//Class for entrepreneurs
class Entrepreneurs {
var name:String?
var netWorth = (0.0, "")
var company:String?
var summary: [String]
var age: Int?
init() {
name = ""
company = ""
summary = [""]
age = 1;
}
}
let markZuckerBerg = Entrepreneurs()
markZuckerBerg.name = "Mark Zuckerberg"
markZuckerBerg.age = 19
markZuckerBerg.company = "Facebook"
markZuckerBerg.netWorth = (35.7, "Billion")
I have several instantiations (more than 5) and I now want to randomly access a member from the Entrepreneur class and display its properties.
I know I will need an Array to hold the class members but I don't think adding each member of the class in an array is the most efficient way to go about it, since I plan on adding hundreds of entrepreneurs eventually.
Any Suggestions?
(Side question: is this the best way to structure such a problem? In other words, If my goal is to have a list of entrepreneurs with information about them, and I want them to display randomly on the screen of a phone as an alert, is creating a class of entrepreneurs the best way?)
Seems to me like you want to randomly select objects from a group of them. To do this you need an array and a random number between 0 and the amount of elements in the array.
Code
let array: [Entrepreneurs] = [a,b,c,...]
let random: Int = Int(arc4random_uniform(UInt32(array.count)))
let selection: Entrepreneurs = array[random]
As far as showing them through and alert I need more details on the question.

Trouble finding the correct syntax creating vars in objects

Up until now I have been creating var inside the classes I made. e.g.
var backpack:Array = new Array("food", "water");
I want to create objects dynamically now like:
player = {};
player.backpack = ("food", "water"); // not the right syntax
OR
player = {backpack:Array = new Array("food", "water")} // not right either.
Any help? Thanks in advance. I can do this with simple vars like int, but can't find the answer to arrays.
ActionScript's generic object properties don't have any variable type associated with them. You assign them one of the following ways.
Example 1
player = {backpack: new Array("food", "water")};
Example 2
player.backpack = new Array("food", "water");
Example 3
player["backpack"] = new Array("food", "water");
You can use square brackets to define literal arrays. Not only is it shorter, but it's also faster (see this post).
The correct syntax for your two examples are
player = {};
player.backpack = ["food", "water"];
and
player = {backpack: ["food", "water"]};
Also, if you find it easier, you can use it in the first line of code you wrote.
var backpack:Array = ["food", "water"];

cakephp - using create() not working as expected

I have a product controller and when I'm saving a new product I want to save some records to another related controller to make a record of what categories the product is associated with.
My code I'm using is:
$this->Product->create();
if ($this->Product->save($this->request->data)) {
$newProductId = $this->Product->getInsertID();
//associate products with categories
foreach($categoriesToSave as $key=>$value) {
$saveArray['CategoriesProduct'] = array('category_id'=>$value, 'product_id'=>$newProductId);
$this->Product->CategoriesProduct->create();
$this->Product->CategoriesProduct->save($saveArray);
$this->Product->CategoriesProduct->clear();
}
}
For some reason though, even if $categoriesToSave has 10 items in it, only the very last one is being saved. So it's obviuosly creating only the one new CategoriesProduct item and saving each record over the top of the last instead of create()-ing a new one.
Can anyone explain what I'm doing wrong and how I can make this work?
The way I would do it would be like this:
//Add a counter
$c = 0
foreach($categoriesToSave as $key=>$value) {
$saveArray[$c]['CategoriesProduct']['category_id'] = $value;
$saveArray[$c]['CategoriesProduct']['product_id'] = $newProductId;
$c++;
}
$this->Product->CategoriesProduct->saveMany($saveArray);
I don't think that is the only way to do it but that should work just fine.
Good luck!

Resources