I have to store an object in my AngularJS code. The values that are to be stored are variables that are passed in a function that is called when a button is clicked.
The basic structure of the object is :
"TopNode" : {
"CreateNode" : {
"ChildNode": {
"LowestNodeOne": "LowestNodeTwo"
}
}
}
All the above variables are obtained from the function parameters. But the problem here is that when I write the variables in the above object, i.e
variableTop : {
variableCreate : {
variableChild : {
variableLowOne : "Value for LowestNodeTwo"
}
}
}
But this code return the variable name itself and not the value stored in it (except for the lowest value variable).
I'm also fine with storing the object as a key-value pair, where the name of the key would also be stored along with its value. But I'm not sure exactly how would the structure of such an object would be?
Any help would be appreciated. Thanks.
Not able to understand the first version of the problem .
Will Edit this answer if i get hold of the problem.
But for your second part of the problem , you can store JSON key value pairs in Hash map like this:
[parent] = parent.child1
[parent.child1] = parent.child1.child
[parent.child1.child] = value
Algo - Traverse map till a value of a key is not a key .
Note : Hash maps and JSON have their own use cases . Usage of Hash Maps as a hierarchical object is not recommended as if the number of child nodes increase there would be a performance hit while traversing to the desired node , Better you go with JSON approach.
Related
I am trying to create a label in openlayers. ( pop-ups I can do) .
My data comes from a PostgreSQL db.
I managed to create an array with the values like this:
var selectedFeatures = [];
ogc.getSource().forEachFeature(function(feature) {
selectedFeatures.push(feature.get("id"),feature.get("datum"),feature.get("fractie"), feature.get("tijd"));
});;
Now, how do I match the actual feature (id), with the right value (id)from the array?
And push this value to a variable?
You could use an object instead of an array, or an array of arrays indexed by the id
selectedFeatures[feature.get("id")] = [feature.get("datum"),feature.get("fractie"), feature.get("tijd")];
I am working with a method which filters the preferences which match with the ids, I am using the contains method, but even though the values are the same, the contains is showing a false in each iteration. The method looks like:
private fun filterPreferencesByIds(context: MyPodCastPresenterContext): List<FanPreferences> {
return context.preferences?.filter {
context.ids.contains(it.id)
}
}
The values of the arrays are:
for the context.ids:
"B52594F5-80A4-4B18-B5E2-8F7B12E92958" and "3998EDE7-F84B-4F02-8E15-65F535080100"
And for the context.preferences:
But even though, when the first and the final ids have the same id value as the context.ids, the contains is false in the debug. I think it could be related with the types in the context.ids rows Json$JsonTextNode. Because when I did the same with numeric values hardcoded the compare is successful.
Any ideas?
Thanks!
If the type of FanPreferences.id is String and the type of context.ids list element is JsonTextNode, you won't find an element equal to the given id string, because it's not of String type.
Try mapping your context ids to the list of strings before filtering:
val ids = context.ids.map { it.toString() }.toSet()
return context.preferences?.filter {
ids.contains(it.id)
}
Note that calling toString() on JsonTextNode might be not the best way to get the string data from it. It's better to consult the API documentation of that class to find it out.
I have this array where I set the keys on the creation. Now in some point in my view I load some more information based on ids (the keys).
var colors = [
"37027" : UIColor(red:150/255, green:57/255, blue:103/255, alpha:1),
"12183" : UIColor(red:234/255, green:234/255, blue:55/255, alpha:1),
"44146" : UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
]
I want to add more colors to this array dynamically. How can I insert new items in the array setting the key? Something like
colors["25252"] = UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
The line above doesn't work, it is just to illustrate what I need.
Thanks for any help
Update: the code above is an example. Below the real code:
var placedBeacons : [BeaconStruct] = []
BeaconModel.fetchBeaconsFromSqlite(completionHandler: {
beacons in
for item in beacons{
self.placedBeacons["\(item.major):\(item.minor)"] = item
}
})
Error: Cannot subscript a value of type '[BeaconStruct]' with an index of type String
To match the key subscripting
self.placedBeacons["\(item.major):\(item.minor)"] = item
you have to declare placedBeacons as dictionary rather than an array
var placedBeacons = [String:BeaconStruct]()
It requires that item is of type BeaconStruct
The code you wrote, it should work. I have used such kind of code and was able to implement successfully. I just tested your code in my end and it's working for me. I declared colors variable globally in my class file and in view did load method added the second code to add another item in my colors array. After printing it out. My output shows full list of array with 4 items and the number of array count return 4 as well.
Please let me know, more details of your scenario so i can help you to figure it out the issue. but looks like it should work.
This question already has answers here:
Difference between JSONObject and JSONArray
(9 answers)
Closed 6 years ago.
What are the difference and advantages of using JSON arrays:
{
thing:[
{ },
{ }
]
}
versus JSON objects:
{
thing:{
{ },
{ }
}
}
The difference between an array and an object is that
Objects are set up using a key and value like:
person.age = 15;
If the key value is a variable, then one could access it like:
var key = "age";
alert(person[key]);
Arrays use an integer[1] index and take a value.
player[1].score += 1000;
[1] Yes, I know, in JavaScript the integer index is really turned into a string behind the scenes. Ignore that. Think of arrays taking an integer value ESPECIALLY when you think of JSON.
Objects- key and value, Arrays- integer. When do you use this or that?
I think of arrays and objects as "is a/an" and "has a" respectively.
Lets use "Fruit" as example.
Every item in fruit array is a type of fruit.
array fruit : [orange, mango, banana]
.
Arrays can contain objects,strings, numbers, arrays, but lets deal with only objects and arrays.
array fruit : [orange:[], mango:{}, banana:{}]
.
You can see that orange is an array too. It implies any item that goes int orange is a type of orange, say: bitter_orange, mandarin, sweet_orange.
for fruit object, any item in it is an attribute of fruit. thus the fruit has a
object fruit :{seed:{}, endocarp:{},flesh:{}}
This also implies that anything within the seed object should be property of seed, say: colour,
JSON arrays represent a collection of objects. In JS, theres a bunch of collection functions off of them such as slice, pop, push. Objects have just more raw data.
The second form you show is actually not valid JSON, as each of the objects in the "thing" object would need some sort or property name to access it by.
To answer your question, the difference is that in the first case, you would access the objects in "thing" using array access like obj.thing[0] or obj.thing[1]. In the second case, if you had proper property declarations you would access like obj.thing.property
Generally in JSON array are used to store a grouping of like items, while object are used to contain grouping of different properties for a single item.
JSON is primarily a language that allows serializing javascript objects into strings. So upon deserializing a JSON string you should get a javascript object structure. If your json deserializes into an object that stores 100 objects called object1 to object100 then that's going to be very inconvenient.
Most deserializers will expect you to have known objects and arrays of known objects so that they can convert the strings into the actual object structure in the language you're using.
Also this is a question that the philosophy of object oriented design would answer you.
A JSON object can be transformed using toJSON:
function kryptonite(key)
{
var replacement = {};
for(var __ in this)
{
if(__ in alias)
replacement[__] = this[__]
}
return replacement;
}
var alias = {"Clark":"","phone":""};
var contact = {
"Clark":"Kent",
"Kal El":"Superman",
"phone":"555-7777"
}
contact.toJSON = kryptonite;
var foo = JSON.stringify(contact)
A JSON array can be transformed using map:
var contact = {
"Clark":"Kent",
"Kal El":"Superman",
"phone":"555-7777",
"home":[{"present":"Metropolis"},{"past":"Krypton"},{"future":"Phantom Zone"}]
}
var filter = {"past":"","future":""}
function junction(value, index)
{
for (var __ in filter) if(value[__]) return value[__]
}
var island = contact.home.map(junction);
So, for sending to individual streams we have to reference the connected netStream we want to send to in some way like this:
sendStream.peerStreams[0].send("MyFunction",param1,param2);
and I have to determine which peer I'm sending to by their ID such as "peerID1234"
I know that you can check the peerID of the stream by doing:
sendStream.peerStreams[0]["farID"]
how can I make my send stream function know to use the array index where the peerID is?
so basically it could be like:
sendStream.peerStreams[where peerStreams[]["farID"] == peerID].send("MyFunction",param1,param2);
Sounds like you'll have to loop through the peerStreams array to find the object that has the right farID property value. Basically you are searching through the array for an item with a specific property value. There is no built-in functionality for this. But you can do it with a simple loop. Something like this:
var correctStream:Object = null;
for each (var stream:Object in sendStream.peerStreams) {
if (stream["farId"] == peerId) {
correctStream = stream;
break;
}
}
correctStream.send("MyFunction",param1,param2);
Note that I don't know what the data type is for the peerStreams object so I just typed it as Object in my example.
There's some other approaches mentioned here but they are just different styles of doing the same thing.