How to get numeric value from array in as3? - actionscript-3

I have an array like this
var records:Object = {};
var arr:Array = [
records["nh"] = { medinc:66303},
records["ct"] = { medinc:65958},
records["nj"] = { medinc:65173},
records["md"] = { medinc:64596},
records["kk"] = { medinc:61321}
];
arr.sortOn("medinc", Array.NUMERIC);
and I have the array sorted numerically. My question is how I can get the numeric value from each record? I want to use that value to set the width of different movie clips.
Something like
object1.width=(record for the [0] position in the array)
object2.width=(record for the [1] position in the array)
object3.width=(record for the [2] position in the array)
etc...
I hope this is clear enough. Thanks for your help!

trace(arr[0]['medinc']); // 61321
Basically, to address a certain field in the nested object, you address it as an associative array with an index of type String.

Related

How to get property from JSON model filled with oData?

Im trying to get property from oData return model. I set data in success callback function from oData to JSON model.
oODataModel.read("/ConnObjSet?$filter=Objecttype eq 'CONNOBJ' and ConnObject eq '20000000002'",
true,
true,
false,
function _OnSuccess(oData, oResponse){
var oJSON = new sap.ui.model.json.JSONModel();
oJSON.setData(oData);
sap.ui.getCore().setModel(oJSON, "ConnectionObject");
},
This is my JSON object in console log and highlighted property I want to get. I want to get every 15 Buspartner number from whole array.
And this is what I tried to get property:
var oLog = sap.ui.getCore().getModel("ConnectionObject").oData.results;
console.log(oLog);
If you have an array of objects, you can get an array of properties from each of these objects by using the Array.map() function.
So in your case:
var aResults = this.getView().getModel().getProperty("/results");
var aBuspartner = aResults.map(function (r) { return r.Buspartner});
var oJSONModel = new sap.ui.model.json.JSONModel();
oJSONModel.setProperty("/resultarray", aBuspartner)
Please try:
var aResults = this.getView().getModel().getProperty("/results");
var oJSONModel = new sap.ui.model.json.JSONModel();
oJSONModel.setProperty("/resultarray",new Array())
for(var i = 0; i<aResults.lenght;i++){
oJSONModel.getProperty("/resultarray").push(aResults[i].Buspartner)
}
You could also try to add a filter and select to your oData.read
The oData-URL
http://services.odata.org/V2/Northwind/Northwind.svc/Products
selects all Product with all their properties
http://services.odata.org/V2/Northwind/Northwind.svc/Products?$filter=UnitsInStock%20eq%2017
shows only Products with "UnitsInStock=17"
http://services.odata.org/V2/Northwind/Northwind.svc/Products?$select=ProductID&$filter=UnitsInStock%20eq%2017
selects only the ProductID of Products with "UnitsInStock=17"
so
oODataModel.read("/ConnObjSet?$select=Buspartner&$filter=Objecttype eq 'CONNOBJ' and ConnObject eq '20000000002'"
...
should get the filtered Buspartners directly.

get key of a object at index x

How to get the key at specified index of a object in Flex?
var screenWindowListObject:Object = {
'something' : 'awesome',
'evenmore' : 'crazy',
'evenless' : 'foolish'
};
I want key at index 1 i.e evenmore.
In JavaScript it can be possible by using the following code.
var keys = Object.keys(screenWindowListObject);
console.log(keys[1]); // gives output 'evenmore'
Is there any equivalent in Flex?
I have an object with unique keys. Values are not unique. I am displaying the values in DropDownList by adding them to an Array Collection. I have to get the key from the Object based on the selected index.
According to Adobe, "Object properties are not kept in any particular order, so properties may appear in a seemingly random order." Because of this, you'll have to invent your own order. This can be achieved by populating an array with your keys, and then sorting that.
function getKeyOrder(hash:Object, sortType:int = 3):Array {
// Returns an array with sorted key values.
/*
1 = CASEINSENSITIVE
2 = DESCENDING
3 = ASCENDING
4 = UNIQUESORT
8 = RETURNINDEXEDARRAY
16 = Array.NUMERIC
*/
var order:Array = [];
for (var k:String in hash) {
order.push(k);
}
var reverse:Boolean = false;
if (sortType == 3) {
reverse = true;
sortType = 2;
}
order.sort(sortType)
if (reverse) { order.reverse(); }
return order;
}
var screenWindowListObject:Object = {
'something' : 'awesome',
'evenmore' : 'crazy',
'evenless' : 'foolish'
};
var orderedKeys:Array = getKeyOrder(screenWindowListObject);
for each (var key in orderedKeys) {
trace(key + ":" + screenWindowListObject[key]);
}
/* Results in...
evenless:foolish
evenmore:crazy
something:awesome
*/
trace("Index 0 = " + screenWindowListObject[orderedKeys[0]])
// Index 0 = foolish
getKeyOrder() returns an array with your keys in ascending order by default. This way, you'll be guaranteed to always have the same sequence of keys, and be able to pull up the index you're looking for. Just be wary when adding more keys, as it will shift each entry depending on where it shows up in the sort.
JavaScript's Object.keys uses the same order as a for..in loop, so in AS3 you could implement it the same way:
function getKeys(object:Object):Array {
var keys:Array = [];
for(var key in object){
keys.push(key);
}
return keys;
}
Note, though, that the enumerable order of keys on an object at runtime is not necessarily the same as you've written it in code.

Finding an item in array knockout

I am trying to assign a variable to an item in an array that has a specific value for a property. For example, I am trying to grab the item that has "Id" value = 15. The way I am currently doing it, I am only returning the first item in the array, no matter the Id value I am inserting.
var credential = ko.utils.arrayFirst(allCredentialsList, function (credential) {
return credential.Id = id;
});
You need to use the === (or ==) comparison operator, not the = assignment operator.
var credential = ko.utils.arrayFirst(allCredentialsList, function (credential) {
return credential.Id === id;
});

Variable Key in Key-Value pairs

So the code that I have working is something like this:
var name:String = "Cashier";
var data:String = "Pay";
arr.push({name:tmpName, data:tmpData});
name, tmpName, data and tmpData are all variables.
However this shows up as "name" and "data" being the key instead of "Cashier" and "Pay"
tmpName & tmpData are setting correctly, however.
Any help would be greatly appreciated.
You'll need to use square bracket notation for dynamically named keys:
var object:Object = {};
object[name] = tmpName;
object[data] = tmpData;
arr.push(object);
I'm doing a PHP to AS3 code conversion and I've created this function to help me with associative arrays declared with dynamic keys (it should work in JavaScript with just a few changes). It might help you as well.
function array(... keysAndValues):Object // Emulates PHP's associative arrays
{
var obj:Object = {};
if (keysAndValues.length % 2 != 0)
{
throw new Error('The number of arguments of array() must be even. To create a non-associative array, use "new Array()" or "[]".');
}
for (var i:int = 0; i < keysAndValues.length; i += 2)
{
obj[keysAndValues[i]] = keysAndValues[i + 1];
}
return obj;
}
That way if I have the keys and values in strings...
var key1:String = 'FirstKey', value1:String = 'aaaaa';
var key2:String = 'SecondKey', value2:String = 'bbbbb';
I can just do...
var myAssoc:Object = array(
key1, value1,
key2, value2
);
Which is really similar to PHP's syntax:
$myAssoc = array(
$key1 => $value1,
$key2 => $value2
);
So you just have to substitute the " => " in a PHP assoc array with ", " when using this array() method. Just make sure the number of arguments is even and you don't mix up keys and values, as it goes key, value, key, value, ...
You can use this lowercase array() method for PHP-like associative arrays and AS3's regular uppercase new Array() declaration for numeric arrays (or just use []). Just remember that when using lowercase array() you're really getting an Object, not an Array, so you should declare the variable which stores it accordingly as an Object.

Store object properties in a 2d array

I have an array of objects that I need to convert to a 2d array so I can write to a Google spreadsheet where each property is written to a cell. I have the function below:
function objectsToArray(objects) {
var outPutArray = createArray(objects.length, objects[0].length);
for (var i in objects) {
for (var j in objects[i]) {
if (objects.hasOwnProperty(i)) {
outPutArray[i][j] = objects[i][j];
}
}
}
return outPutArray;
}
example object:
object {
name: John
phone: 555-5555
email: john#john.com
}
The problem is that instead of putting the properties value in the array element (outputArray should look like [[John, 555-5555, john#john.com],[..., ..., ...]] it adds the properties to each array element.
In the first part of your function,
function objectsToArray(objects) {
var outPutArray = createArray(objects.length, objects[0].length);
it looks like you are assuming objects is already a 2D array. I'm going to assume that objects is a 1D array of objects like this. [{prop:value...},{...},{...}].
Now what you want to do is generate 2 numerical indices from this data. You will want to ensure that "column 1" of the 2D array is the same property for all objects.
So your first for loop should be over the properties. Also, keep an index so you know what number property you are on.
var j = 0;
for (var prop in objects[0]) {
Then you should do a loop over all the objects. So the idea is that first you will select "name", then go through all the objects, adding the "name" field to the 2D array for each object.
for (var i in objects) {
outPutArray[i][j] = objects[i][prop];
}
j++;
}
I think the main issue that you were seeing is because you weren't using numeric indices. (var j in objects[i]: this defines j as a property, such as "name", not a numeric index, like you were expecting).
Here's one way...
function myFunction() {
var objects = {};
objects[0] = {"name": "John", "phone": "555-5555", "email": "john#john.com"};
objects[1] = {"name": "Mary", "phone": "444-4444", "email": "mary#mary.com"};
var outputArrary = objectsToArray(objects);
Logger.log(outputArrary);
}
function objectsToArray(objects) {
var outputArray = [];
for (var i in objects)
outputArray.push([objects[i].name, objects[i].phone, objects[i].email]);
return outputArray;
}