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);
Related
lets say I have a json array called arr, which contains some number of json objects, jsobj1, jsboj2,... jsbojn. if I want to add a new json object jsobjm inside of jsobj2 how would I do that?
I tried to do arr.get(1).put("jsobjm", jsobjm), but I get the error cannot find symbol, pointing to the . before the put().
Well you could do this (instead of manipulating the array as a String):
Convert the JSON array into it's object equivalent and add the object you want using the programming language you use.
Convert the object back to JSON
eg using Javascript
let arr = '[{\"name\":\"Ford\"}]';
//convert to object
let objArray = JSON.parse(arr);
let obj = objArray[0];
//add the other object you want into the first object
obj.description = {"reason":"My fav car"};
console.log(obj);
//convert everything back to string
console.log(JSON.stringify(obj));
JSfiddle: https://jsfiddle.net/allkenang/tuvxrgj3/8/
I am currently in a bit of a bind.
struct sectionWithDatesAsName {
var sectionName : String
var sectionObjects : [SoloTransactionModel]!
init(uniqueSectionName: String?, sectionObject: [SoloTransactionModel]?) {
sectionName = uniqueSectionName ?? "nil"
if let section = sectionObject {
sectionObjects = section.reversed()
}
}
}
I currently have an array of sectionWithDatesAsName. And I can work with it, display in the tableView among other things.
The bind comes up when I want to check some information in the sectionObject before displaying it on the tableView.
I want to check the type of the sectionObject which is saved in the object itself.
How do I check the information in the sectionObject without slowing down the app? Or have a horrible time complexity calculated?
(Note: I can't change the format of the struct has this has already been used by a whole lot of other processes)
Write a function in your sectionWithDatesAsName with the signature filteredSections(type: sectionType) -> sectionWithDatesAsName
(If you don't have the ability to edit the definition of sectionWithDatesAsName you can create an extension that adds the above function)
If the sectionWithDatesAsName is defined elsewhere, define this function in an extension.
When you call it, build a new sectionWithDatesAsName object by filtering the arrays to match the specified type.
Use the resulting filtered sectionWithDatesAsName object as the data model for your table view. It will be built once and used for the lifetime of the tableView, so you will pay an O(n) time cost to filter it once when you create it.
I have a database (parse-server) from which I can fetch objects which contain information. Some of the information in the properties of the objects are used to populate labels on table views. The way I have been populating, let's say, the userName and userLike labels are as follows:
Appending Different Arrays with the objects properties
var userName = [String]()
var userLikes = [String]()
func query(){
let commentsQuery = PFQuery(className: "UserStuff")
commentsQuery.findObjectsInBackground { (objectss, error) in
if let objects = objectss{
for object in objects{
self.userName.append(object["userName"] as! String)
self.userLikes.append(object["userLikes"] as! String)
}
}
}
}
Ignore the fact that I don't have a .whereKey or any else statements to handle other cases... this is bare bones just for illustration of the question. Anyway, in this method, the userName and userLikes arrays are iterated through to populate the labels. The for object in objectss{} ensures that the indexes in one array (whether index 0,1,2,3,etc...) refers to/comes from the same object as the value in the index of the other array. However, I was wondering if would be better to do it as follows:
Appending the whole object to a PFObject array
var userObjects = [PFObject]()
func query(){
let commentsQuery = PFQuery(className: "UserStuff")
commentsQuery.findObjectsInBackground { (objectss, error) in
if let objects = objectss{
for object in objects{
self.userName.append(object)
}
}
}
}
With this method I could instead populate the labels with something like:
userNameLabel.text = String((userObjects[0])["userName"])
In this method all properties of the object would be accessible form the same array. I can see that this may have some advantages, but is this definitively the better way to do it/should I switch immediately?
I am going to say that the answer is that the latter of the two is probably the better method. This is because in the former, the information from a particular object is only linked between arrays by the order in the array. Any accidental or incorrectly scripted functions involving .append or .remove could skew the order between arrays and then an object's name might be the 3rd index in the nameArray but its likes may end up being the 4th index in the likesArray and it would be difficult to amend this issue. With the latter method, all information regarding an object's properties are linked to the object itself in the array and this issue is avoided.
Question
How can I create an array of objects containing Realm objects?
Code
let realm = try! Realm()
let data: [A] = realm.objects(A)
Error
Cannot invoke 'objects' with an argument list of type '(Object.type)'
How can I create an array of objects containing Realm objects?
From your code sample, I'll further assume that you want to make an array from a Realm Results, not just "standalone" Realm objects.
Since Results conforms to SequenceType, you can use SequenceType.map() to convert it into an array:
let arrayFromResults = results.map({ $0 })
Note, however, that this is almost always the wrong pattern to use.
From your tweet on the same topic, a preferable way to do this would be to encode what you want to display on screen as a Realm query:
self.results = realm.objects(A).filter("poppedOff == NO")
And "popping off" an object (whatever that means) would update the poppedOff property of that object.
Since Realm Results are auto-updating, this won't risk getting out of sync with the contents of the Realm, unlike the array conversion approach, which would have to be updated on every Realm change notification.
I've imported several images into an actionScript 3 document. I've turned them all into symbols (movie clips) and given them instance names to reference from ActionScript.
Ok, so I'm putting the instances into an array so I can loop through them easily, but for some reason, whenever I'm putting in the instance name, I do a trace on the value in the array and it's giving me the symbol object back, rather than the instance object.
Basically trying to loop through the array to make each instance's visibility = false
Here's a sample:
var large_cap_extrusion_data: Array = new Array();
large_cap_extrusion_data[0] = large_cap_extrusion_menu_button;
large_cap_extrusion_data[1] = extrusion_border_large_cap
large_cap_extrusion_data[2] = "Large Cap";
large_cap_extrusion_data[3] = large_cap_main_menu_button;
var extrusion_data: Array = new Array();
extrusion_data[0] = large_cap_extrusion_data;
trace(extrusion_data[0][0]);
The traces gives:
[object large_cap_menu_button]
(the parent symbol)
rather than:
"large_cap_extrusion_menu_button"
I'd be very grateful if someone could tell me where I'm going wrong...
when you trace and object, by default it describes it type. What you want is the "name" property of the object.
Try this:
trace(extrusion_data[0][0].name);
that should give you the instance nema of the large_cap_menu_button rather than the class description. Either way, you have the right object I bet.