Variable Key in Key-Value pairs - actionscript-3

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.

Related

Unable to add new key value into an existing JSON Array with JSON objects

Here is what I have tried.
I have tried dot notation and quotes. None of them seem to work. What exactly could be the problem?
var clientsList;
Client.find({}, function(err, clients) {
clientsList = clients;
// I have 10 clients in the loop
for (var j = 0; j < clientsList.length; j++) {
var x = clientsList[j];
x.count = "20";
//x["count"] = "20";
console.log(x);
}
});
Existing Client object
{"name":"abcd", "email":"abc#gmail.com"}
I'm unable to add the count key value pair into the client object. What could be the problem?
I suspect the object you're being given by Client.find has extensions prevented (it's sealed or frozen).
You can create a new object with the original's own, enumerable properties plus your count property using ES2018 spread notation:
x = {...x, count: "20"};
...or ES2015's Object.assign:
x = Object.assign({}, x, {count: "20"});
If the array is also sealed or frozen, you can copy it and its objects like this:
clientList = clients.map(client => {
return {...client, count: "20"}; // Or with `Object.assign`
});
or even with the concise form of the arrow function:
clientList = clients.map(client => ({...client, count: "20"}));
Side note: This pattern:
var clientsList;
Client.find({}, function(err, clients) {
clientsList = clients;
// ...
});
...often suggests that you intend to use clientsList in code following the Client.find call and expect it to have the result from that call's callback. See this question's answers for why, if you're doing that, it doesn't work.

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.

assign Json value to a variable using $.each()

I am trying to pass the result of this query as a Json string to Jquery so that I can assign the value to a JQuery variable. Actually there will be more than one key:value pair but I am illustrating my problem with a single pair for simplicity. I am able to console.log the index and value however when I try to assign the value to a variable I get an "undefined" message. I have done this successfully elsewhere and am not sure what i am missing here:
$query = (
"SELECT MedCondPrimary, Count(MedCondPrimary) as Count
FROM Comments
WHERE MedCondPrimary='Arthritis'");
$result = mysqli_query($dbc, $query);
WHILE($rows = mysqli_fetch_array($result)) {
$medcond = $rows['MedCondPrimary'];
$array3[$medcond] = $rows['Count'];
};
$json_count=json_encode($array3);
echo $json_count; // {"Arthritis":"26"}
JQ:
var tally = ;
console.log(tally);// Object { Arthritis="26"} should be a string?
$.each(tally, function(index, value) {
console.log(index+":"+value); //Arthritis:26
var arthritis = value.Arthritis;
console.log(arthritis); //undefined
});
Your jQuery code should be using each() instead of $.each() here.
$( tally ).each(function( index, obj ) {
console.log( index + ":" + obj.Arthritis); // Arthritis:26
var arthritis = obj.Arthritis;
console.log( arthritis ); // 26
});
each() passes the object while $.each() passes property-value pairs for an object. You're $.each() at the other place must be working because you passed it an array as shown below:
// iterating an array
$.each( [{Arthritis:26}], function( index, obj) {
console.log( obj.Arthritis ); // 26
});
PHP Edit :
$json_count=json_encode($array3);
echo "[" . $json_count . "]";

Javascript: Using reviver function, I seem can't get to alter all the keys, while concating the numbers

I just want to change all the keys in batchesX. But I can't seem to alter all keys, because of concat. This is what I learned from post.
Please advise how I can change all keys with numbers.
var batchesX = '[{"batch":"0010002033"},{"batch":"0010001917"},{"batch":"0000020026"},{"batch":"0000017734"},'+
'{"batch":"0000015376"},{"batch":"0000014442"},{"batch":"0000014434"},{"batch":"0000014426"},'+
'{"batch":"0000013280"},{"batch":"0000012078"},{"batch":"0000012075"},{"batch":"0000012072"},'+
'{"batch":"0000011530"},{"batch":"0000011527"},{"batch":"0000011342"},{"batch":"0000010989"},'+
'{"batch":"0000010477"},{"batch":"0000008097"},{"batch":"0000007474"},{"batch":"0000006989"},'+
'{"batch":"0000004801"},{"batch":"0000003566"},{"batch":"0000003565"},{"batch":"0000001392"},'+
'{"batch":"0000001391"},{"batch":"0000000356"},{"batch":"0000"},{"batch":"000"},{"batch":""},'+
'{"batch":null}]'; // 30 elements
//in JSON text
var batchi = "batch";
var obj_batchesY = JSON.parse(batchesX);
console.debug(obj_batchesY);
var obj_batchesYlength = obj_batchesY.length;
console.debug(obj_batchesYlength);
var obj_batchesX = JSON.parse(batchesX,
function(k,v)
{
for(var i=1; i <= obj_batchesYlength; i++ )
{
if(k=="batch")
{
this.batchi.concat(string(i)) = v;
}
else
return v;
}
}
);
console.debug(obj_batchesX);
Is the code too long winded?
Many thanks in advance.
Clement
The return value of the reviver function only replaces values. If you need to replace keys, then use stringify and replace before the parse call, like this:
JSON.parse(JSON.stringify({"alpha":"zulu"}).replace('"alpha":','"omega":'))
Here is how to replace all numeric keys:
function newkey()
{
return Number(Math.random() * 100).toPrecision(2) + RegExp.$1
}
//Stringify JSON
var foo = JSON.stringify({"123":"ashanga", "12":"bantu"});
//Replace each key with a random number without replacing the ": delimiter
var bar = foo.replace(/\d+("?:)/g, newkey)
//Parse resulting string
var baz = JSON.parse(bar);
Make sure each replaced key is unique, since duplicate keys will be removed by the parse method.

How to browse keys of an object

I'm looking to get/display the key name of an object in AS3.
I have for example :
var obj:Object = {key:"value"};
Here I try to display "key" (not its value).
The goal is to be able to merge two objects together.
Any idea ?
Thanks !
To get at the keys of an object you need to loop over them:
for (var key:String in obj) {
trace("key:", key, "value:", obj[key]);
}
Thus, merging obj1 and obj2 (with anything from the second overwriting the first) would look like this:
var merged:Object = {};
var key:String = "";
for (key in obj1) {
merged[key] = obj1[key];
}
for (key in obj2) {
merged[key] = obj2[key];
}