Counting object pairs in JSON array - javascript

ive got a problem getting parameters from a json chain, the json I got looks something like this
[{"aa":"bb","ccc":"ddd","eeee":"ffff","ggggg":"hhhhh","iiiiii":"jjjjjj","kkkkkkk":"lllllll"}]
Im trying to count how many pairs there are inside the '{}' but i dont know how. I tried json.length and json[0].length, the first one gave me back the value '1' and the second one undefined.

Your json object is an array containing one object. So the length is 1. The object in the array has multiple properties (key/value pairs).
So in most modern browsers (except IE), this would work for you:
Object.keys(json[0]).length
Check out the answers here of various techniques for iterating/counting properties of an object in JavaScript:
How to efficiently count the number of keys/properties of an object in JavaScript?

Related

Access Array with String key

I have two variables with JSON files. The first is a list of keys looks like this:
keylist = ["key1","key2","key3"]
The second one is generated from a database and looks like this:
data = {
"key1"{
#further data
},
"key2"{
#further data
},
"key3"{
#further data
}
}
Now I want to access the second element of the database with the key from the keylist
data.keylist[1];
Which doesn't work because the return of keylist[1] is a String? I did some research and the use of the window function was proposed. So I tried this:
window["data." + keylist[1]]();
Which leads to a "is not a function" error. What can I do to solve this problem?
As simple as that:
const mydata = data[ keylist[1] ];
Also, your code is correct from the point of syntax, but it tells completely different than you expect it to tell.
data.keylist[1];
tells JS that you expect to have an object called data which has a property called keylist and which is (most likely) type of array, and you want to get the second element of this array.
PS: And one more point here. Your question title is not completely correct because of the difference between Arrays and Object in JS.
There is no "string keys" for arrays in JS, so you cannot "access array with a string key". Well, truly speaking there are, but not for items of array. Array items only have numeric index, which you can use to access it. Objects, in contrast to arrays, may have named properties. So when you see something like that: data = myVar['data'], you can tell that you're dealing with an object, while data = someVar[0] can be both, an Array (most likely) or also an Object with key named '0'.
I don't think the issue you're having with your first example is because it returns a key. I believe the issue is because data doesn't have a property called keylist. Instead of that, try it as
data[keylist[1]]
and see if that works for you. The reason this one should work is that, in this situation, Javascript will evaluate the string return of keylist[1] and then use it as a string index for the data variable. Let me know if this works out for you :D
You can try using using something like this.
data[keylist[1]]

JavaScript assoziativ array :/

what's the best way in JavaScript to store values in an assoziative array? I tried a lot of things and it always brakes somehow.
I tried something like:
var test = [];
for(var prop in json) {
test[prop] = json[key];
}
this works and i get a cool array then i can actually use. However calling test.length gives me 3 when there should be 10 items, it sometimes gives me 0 when there should be at least 8 items.
What do i do wrong? What's the best way to go here to get an assoziative array going which i can use properly like in Java?
Everything is an object in JavaScript. foo['bar'] is the same as foo.bar. Array is just an object with some predefined methods that let it emulate what you would call a numeric array in PHP or just an array in almost any other language. JavaScript objects work like associative arrays in PHP. The general non-PHP name for it is hash.
So, to address your problem with length, it is a predefined property of an array object. Using it on an object that isn't an array will not give you the results you are expecting. To count the number of properties in an object, you can use
Object.keys(obj).length
in modern browsers. keys() function gets an array of keys from a hash, so it will have a correct length property.
If you wish to support older browsers, you have to iterate through object properties and count them manually. Be aware that for (var prop in json) will also iterate through the properties of every object in the prototype chain, so you might want to check if a property is object's own property using hasOwnProperty() method.

How can I get the length of a deferred Model in CanJS?

I am getting a model deferred object with a structure like this:
How can I find out how many objects are present inside this object (in this case, three). If I use Object.keys(myObject).length, it includes the object observer and other data also like _computeBindings,_bindings etc. I have even tried to use hasOwnProperty while calculating the length but its not giving me desired result.
One way I can figure out is to iterate over the index and get the last index value like this:
can.each(myObject,function(myObject,index){
// Get the last index value and put it into some variable
});
Is there an API for this?
can.Map has a keys function that will give you an Array of the keys in your Map and from that you can get how many Objects by checking that Array's length.
Using a can.List as your data structure would also work. The keys in your data are numeric and you need to check the length, all things that can.List is built for.
Try using myObject.attr('length')
The model _data attribute contains a copy of just the model without the bindings. The easiest way to do this is to use:
Object._data.length

Using a for loop to populate an array with objects

I have a function that takes an array, consisting of 3 sets of strings. For each set of strings, the function should spit out 2 resulting integers/numbers.
Link to the jsfiddle of work in progress
So if the input is
["10:00AM-12:30PM","02:00PM-02:45PM","09:10AM-09:50AM"]
I'm trying to get the function, by using a for-loop, to spit out 2 minute counts for each element of the array (a total of 6 minute counts, 2 per string).
I'm thinking I need the results stored in an object? Or maybe an array, consisting of objects? I'm a little bit confused here.
I'm confused as to how to organize it so that whatever is returned from the function, I can easily access it.
So maybe an array of 3 objects is returned is the best way to do it, with each object consisting of:
1st identifier key: an identifier of some sort (perhaps using the [i] from the for loop),
2nd key/property time1min: with the value being time1min (which is the 1st minute count),
3rd property time2min: with the value being time2min for that string.
As you can see from my jsfiddle above, I'm lost as to how to output to an object, or to an array of objects.
results is an array; so results[0].time1min
Try using console.log(results); instead. It plays nicer than alerts.

What is meant by obj[''] in Javascript?

Toward the bottom of this javascript file, there is a line
return map[""];
where map is an associative array of objects with parent/child relationships. After calling map[""] the returned structure is a transformation into a hierarchical array. What is really going on under the hood here and where is this syntax documented? (It's hard searching for such empty strings on the net.)
It just reads the empty string property of map, just like how this:
map["a"]
is the same as
map.a
However, you can't just do
map.
so that's why they do
map[""]
This is generated by the function find which ends when the strings become empty, which is why the final element will be found in map[""].

Categories