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];
}
Related
I am receiving the JSON object as a list of objects:
result=[{"key1":"value1","key2":"value2"}]
I am trying to retrieve the values from this list in Node.js. I used JSON.stringify(result) but failed. I have been trying to iterate the list using for(var key in result) with no luck, as it prints each item as a key.
Is anyone facing a similar issue or has been through this? Please point me in the right direction.
If your result is a string then:
var obj = JSON.parse(result);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
console.log(obj[keys[i]]);
}
Lookslike you are pointing to wrong object.
Either do like
var result = [{"key1":"value1","key2":"value2"}];
for(var key in result[0]){ alert(key);}
or
var keys = Object.keys([{"key1":"value1","key2":"value2"}][0]);
alert(keys);
Okay, assuming that result here is a string, the first thing you need to do is to convert (deserialize) it to a JavaScript object. A great way of doing this would be:
array = JSON.parse(result)
Next you loop through each item in the array, and for each item, you can loop through the keys like so:
for(var idx in array) {
var item = array[idx];
for(var key in item) {
var value = item[key];
}
}
Wouldn't this just be:
let obj = JSON.parse(result);
let arrValues = Object.values(obj);
which would give you an array of just the values to iterate over.
A little different approach:
let result=[{"key1":"value1","key2":"value2"}]
for(let i of result){
console.log("i is: ",i)
console.log("key is: ",Object.keys(i));
console.log("value is: ",Object.keys(i).map(key => i[key])) // Object.values can be used as well in newer versions.
}
try this code:
For result=[{"key1":"value1","key2":"value2"}]
Below will print the values for Individual Keys:
console.log(result[0].key1)
console.log(result[0].key2)
This is for JsonObject (not JsonArray per se). p is your jsonobject the key pairs are key and p[key]
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
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.
I want to bind my ng-model with JSON object nested key where my key is in a variable.
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
Here I want to get value 5 from data JSON object.
I found the solution to convert "course.sections.chapter_index" to array notation like course['sections']['chapter_index'] this. but don't know how to extract value from data now
<script type="text/javascript">
var BRACKET_REGEXP = /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/;
var APOS_REGEXP = /'/g;
var DOT_REGEXP = /\./g;
var FUNC_REGEXP = /(\([^)]*\))?$/;
var preEval = function (path) {
var m = BRACKET_REGEXP.exec(path);
if (m) {
return (m[1] ? preEval(m[1]) : m[1]) + m[2] + (m[3] ? preEval(m[3]) : m[3]);
} else {
path = path.replace(APOS_REGEXP, '\\\'');
var parts = path.split(DOT_REGEXP);
var preparsed = [parts.shift()]; // first item must be var notation, thus skip
angular.forEach(parts, function (part) {
preparsed.push(part.replace(FUNC_REGEXP, '\']$1'));
});
return preparsed.join('[\'');
}
};
var data = {"course":{"sections":{"chapter_index":5}}};
var obj = preEval('course.sections.chapter_index');
console.log(obj);
</script>
Hope this also help others. I am near to close the solution,but don't know how can I get nested value from JSON.
This may be a good solution too
getDeepnestedValue(object: any, keys: string[]) {
keys.forEach((key: string) => {
object = object[key];
});
return object;
}
var jsonObject = {"address": {"line": {"line1": "","line2": ""}}};
var modelName = "address.line.line1";
var result = getDescendantPropValue(jsonObject, modelName);
function getDescendantPropValue(obj, modelName) {
console.log("modelName " + modelName);
var arr = modelName.split(".");
var val = obj;
for (var i = 0; i < arr.length; i++) {
val = val[arr[i]];
}
console.log("Val values final : " + JSON.stringify(val));
return val;
}
You are trying to combine 'dot notation' and 'bracket notation' to access properties in an object, which is generally not a good idea.
Source: "The Secret Life of Objects"
Here is an alternative.
var stringInput = 'course.sections.chapter_index'
var splitInput = stringInput.split(".")
data[splitInput[1]]][splitInput[2]][splitInput[3]] //5
//OR: Note that if you can construct the right string, you can also do this:
eval("data[splitInput[1]]][splitInput[2]][splitInput[3]]")
Essentially, if you use eval on a string, it'll evaluate a statement.
Now you just need to create the right string! You could use the above method, or tweak your current implementation and simply go
eval("data.course.sections.chapter_index") //5
Source MDN Eval docs.
var data = {
"course": {
"sections": {
"chapter_index": 5
}
}
};
var key = "course['sections']['chapter_index']";
var keys = key.replace(/'|]/g, '').split('[');
for (var i = 0; i < keys.length; i++) {
data = data[keys[i]];
}
console.log(data);
The simplest possible solution that will do what you want:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']";
with (data) {
var value = eval(key);
}
console.log(value);
//=> 5
Note that you should make sure key comes from a trusted source since it is eval'd.
Using with or eval is considered dangerous, and for a good reason, but this may be one of a few its legitimate use cases.
If you don't want to use eval you can do a one liner reduce:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
key.split(/"|'|\]|\.|\[/).reduce((s,c)=>c===""?s:s&&s[c], data)
let's say you're passing an object to a function
{title:"my title", data:"corresponding data"}
how can I get the function to know what the names of the items/sub-objects are (title and data) without specifying them?
You can use a for loop as follows:
for (var key:String in obj) {
var value:String = obj[key];
trace(key + ": " + value);
}
Or use the introspection API.
The Flex 3 Help page on Performing Object Introspection has a good overview of these.
You can use a for(String in Object) loop like so:
var i:String;
for(i in object)
{
var key:String = i;
var value:Object = object[i];
// do stuff with key/value
}
PS it would make more sense obviously to use key in the loop, my example is done for the sake of demonstration.
Why was this downvoted.. Because I didn't do a function?
function findKeys(obj:Object):Array
{
var ar:Array = [];
var i:String;
for(i in obj)
{
ar.push(i);
}
return ar;
}
var ob:Object = {things:"value", other:5};
trace(findKeys(ob)); // other,things
how to compare two arraycollection
collectionArray1 = ({first: 'Dave', last: 'Matthews'},...........n values
collectionArray = ({first: 'Dave', last: 'Matthews'},...........n values
how to compare..if equal just alert nochange if not alert chaged
If you just want to know if they are different from each other, meaning by length, order or individual items, you can do the following, which first checks to see if the lengths are different, then checks to see if the individual elements are different. This isn't terribly reusable, it's left as an exercise for the reader to split this apart into cleaner chunks :)
public function foo(coll1:ArrayCollection, coll2:ArrayCollection):void {
if (coll1.length == coll2.length) {
for (var i:int = 0; i < coll1.length; i++) {
if (coll1[i].first != coll2[i].first || coll1[i].last != coll2[i].last) {
Alert.show("Different");
return;
}
}
}
Alert.show("Same");
}
/* elements need to implement valueOf
public function valueOf():Object{}
*/
public static function equalsByValueOf(
first:ArrayCollection,
seconde:ArrayCollection):Boolean{
if((first==null) != (seconde==null) ){
return false;
}else if(!first && !seconde){
return false;
}
if(first.length!=seconde.length){
return false;
}
var commonLength:int = first.length;
var dictionary:Dictionary = new Dictionary();
for(var i:int=0;i<commonLength;i++){
var item1:Object = first.getItemAt(i);
var item2:Object = seconde.getItemAt(i);
dictionary[item1.valueOf()]=i;
dictionary[item2.valueOf()]=i;
}
var count:int = 0;
for (var key:Object in dictionary)
{
count++;
}
return count==commonLength;
}
/* valueOf sample
* something like javaObject.hashCode()
* use non changing fields(recommended)
*/
public function valueOf():Object{
return "_"+nonChangeField1+"_"+nonChangeField2+"...";
}
I was going to say this.
if(collectionArray === collectionArray1)
But that wont work (not triple = signs). As === is used to see classes.
I would write a function called check if object exists in array.
Create an array to hold elements that are not found. eg notFound
in Collection1 go through all the element and see if they exist in Collection2, if an element does not exist, add it to the notFound array. Use the function your created in step1
Now check Collection2, if an element is not found add it to the notFound array.
There is no 5.
Dude, use the mx.utils.ObjectUtil... the creators of actionscript have already thought about this.
ObjectUtil.compare(collection1, collection2) == 0;