I have this array and I want to count total numbers into this, can anyone please let me know how can i achieve this using pure javascript
var total = {
"numbers":{
"1":"9897877884",
"2":"9867543234",
"3":"7898879900",
"4":"1234567890"
}
}
You could use Object.keys(total.numbers).length. The first part returns an array with the keys and the second gets the length of it.
var total = { "numbers": { "1": "9897877884", "2": "9867543234", "3": "7898879900", "4": "1234567890" } };
console.log(Object.keys(total.numbers).length);
Object.keys()
The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
Array#length
The length property represents an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
Related
This is a follow up to a previous question I asked:
Sort JSON response by key value
So I know that objects cannot be sorted using the .sort method and if I push each object into an array, I can sort it the way I want.
Why does .sort not work on this:
{ A:{...}, B:{...}, C:{...} }
but works on this:
[ {...}, {...}, {...} ]
It's still accessing and working with object properties in both examples, right?
Here's some code:
var query = {
"736":{
ns: 42,
pageid: 12,
lang: "en",
index: 3
},
"421":{
ns: 12,
pageid: 36,
lang: "en",
index: 4
},
"102":{
ns: 2,
pageid: 19,
lang: "en",
index: 1
}
};
var queryArr = [{ns: 42, pageid: 12, lang: "en", index: 3}, {ns: 12, pageid: 36, lang: "en", index: 4}, {ns: 2, pageid: 19, lang: "en", index: 1}];
query is an object with multiple objects in it, and queryArr is an arry with multiple objects in it. If I wanted to sort query by its index key's value, I'd have to convert it to an arry first, and then run .sort on that array, correct?
What I want to know is why. What prevents query from being sorted, but allows the objects inside queryArr to be sorted? They're both still objects right? The only difference is the outer body is an object in the first, and an array in the second - but it's still working with objects when sorting.
My sort function still referneces the index using the object property accessor:
queryArr.sort(function(i,j){
return j.index - i.index;
});
Array object is object where the positive integer keys are used:
a = [, 1]
a[.1] = .1
a[-1] = -1
console.log( a )
console.log( { ...a } )
If the order of the properties can't be guaranteed, then for example array object [0, 1] can be stored as { "0": 0, "1": 1 } or { "1": 1, "0": 0 }.
Most array looping constructs will look for the "0" property before the "1" property, so the property order doesn't really matter.
Sorting array doesn't change it's properties order, but swaps the values associated with the properties.
Arrays are a special way of sequentially storing data. In the earliest implementations, this would be done by actually storing the array objects sequentially in memory. And resorting would actually physically move the objects in memory. So in your example where you have indices 102, 421, and 736. If you translated this to an array, you would actually have an array of length 737. 0 to 101 would be undefined, then you would have your object at 102. 103 to 420 would be undefined, then object 421. Et cetera.
Good to note that in your example when you translated your object into an array, you lost your keys (102, 421, 736). They simply became (0,1,2). In your example maybe this was okay, but if you had an object with properties like width, height, length, having these replaced with simple array indices like 0,1,2 would be a pretty significant loss of information.
Objects don't work the same way at all. They are not designed to store data sequentially, but hierarchically. So you can have a key 102 that points to an object, but you don't have to have keys 0-101. And key 102 doesn't designate the "order" of the item. It's just a name, and it could just as easily be length or fred or green as 102.
This mirrors reality. For example you might have an array to store a group of people, perhaps starting in order of age. And you could re-sort the list by different properties, like alphabetical by last name, or by height, etc.
But if we look at the objects within that array, it really makes no sense to talk about the order of firstName, lastName, height, weight, age, etc. There isn't really any "order" to speak of: weight doesn't have to come before height, or vice versa. And some people may like to see Last,First, while others prefer First Last. These properties are things we mostly want to be able to access directly by name, so an array isn't really ideal. We want named properties. Hence an object. Don't be confused just because you chose numbers as your property names...they're still names, not indices.
However it is of course possible to iterate all the properties of an object, and it is even possible to control the order in which you iterate them. Traditionally in javascript this iteration was done with the for...in syntax, which goes all the way back to es1. But you couldn't control the order in which the object's keys were iterated. To control order we would have to use for...in to populate an array of keys, then sort the array, then re-loop over the array.
However, it is possible in the newer es6 javascript world to iterate in some great new ways. For example, you can use Object.keys() to get an array of all the object keys (property names), and then you could sort this array. Saves the step of populating an array with for...in.
Another more advanced possibility in es6 (which uses Object.keys) is to actually make the object itself iterable by adding a Symbol.iterator. Again, this only works in es6+.
However the Symbol.iterator gives you a lot of power. This is what it looks like:
query[Symbol.iterator] = function*() {
let properties = Object.keys(this).sort();
for(let p of properties) {
yield {key:p, value:this[p]}
}
}
Once you add this iterator to the object, now you can use things like for...of. And in this example I added a .sort(), so this would iterate over the object's properties in ascending numeric order by key: 102, 421, 736. And since we are yielding an object with key and value, we are still able to see the key value, which we would NOT have if we had just translated to an array.
for(let {key,value} of query) {
console.log(key);
}
I am confused regarding javascript arrays and how the indices work in these arrays. The length of the array is always 0 no matter how many key value elements are there in the array. Also we can see that the array has only two elements provided that the key is string. Lets consider scenario 1, i have following code.
arr = [];
arr['home'] = 1234;
arr['cat'] = 12345;
console.log(arr.length);
console.log(arr);
Now consider second scenario, i have an empty array and i assign some number to the 20th index of the array. Then when i output the array, the length shows 21 with all the other locations being 'undefined'.
arr = [];
arr[20] = 20;
console.log(arr.length); // Length shows 20 Size of array increased to 21
Now in the third scenario i will assign both numbered indices and string indices and it shows another strange behavior. The length of the array doesn't count the value with string based index. Even though i have 4 number indices and one string based index. So the length should be 6 but the length shows 5.
arr = [];
arr[4] = 4;
arr['home'] = 'home';
console.log(arr);
Now i have two questions.Firstly, Why is the length function not considering string indexed item? Secondly, Why in the case of numbered indices, does the array size is increased to atleast that number?
You have to understand that JavaScript arrays are objects, with some additional behavior. Just like objects, you can assign properties to them.
If the property's name is a numeric string and there is no higher numeric key, the length property is updated. Non-numeric keys don't affect the length property.
The methods in Array.prototype (filter, slice, ...) only work with the numeric keys of the array.
Javascript doesn't have associative arrays like you see in PHP. It has arrays, which have a numerical index associated with the value, and then it has objects which are mapped key => value.
Javascript Arrays and Javascript Objects
const arr = [1, 2, 3, 4, 5, 6, 7];
console.log(arr.length); // outputs 7
const obj = {}
console.log(obj.length); // undefined
// set the key => value for obj from arr
arr.forEach(a => obj[a] = a);
console.log(obj[0]); // undefined
console.log(obj[1]); // 1
console.log(arr[0]); // 1
console.log(arr[1]); // 2
JS Bin
In the example above, you can see that arr is an array and its values are mapped index => value, while obj is an object and its values are mapped key => value. Objects can function as hash maps/associative arrays, but arrays cannot.
If you were to want to get the number of values in an object/hash map, you can always do...
Object.keys(obj).length
This is because Object.keys(...) returns the keys of an object as an array.
For an accurate answer, I should clarify that arrays are objects, however, they function differently than an object inherently does. Per the docs, arrays are "high-level, list-like objects"
How to find the length of the ARRAY using ES6:
var x = [{a:"apple", b:"Baloon"},{a:"elephant", b:"dog"}];
var results = x.filter(aValue => aValue.length > 3);
console.log(results);
Note:
aValue.length would have worked if this is individual list of array. However, since these are values assigned to properties. Ex; a: apple, diff approach required.
What's the correct code that I need to replace "aValue.length" to find the length of the value greater than 3, so the answer would be apple, baloon and elephant ?
This will work for your needs
var results = x.filter(val => Object.keys(val).length > 3)
The Object.keys() method returns an array of all the keys contained in your object.
Objects do not have a length property. But there is a little trick with which you can have the number of keys of an object.
There are 2 methods that can be used. Object.getOwnPropertyNames(val).length and Object.keys(val).length
However, there is a little difference between the two. Object.getOwnPropertyNames(a) returns all own properties of the object a. Object.keys(a) returns all enumerable own properties.
As per the description of the Object.keys on MDN:
Object.keys returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.
It includes the following example:
// array like object with random key ordering
var an_obj = { 100: "a", 2: "b", 7: "c"};
alert(Object.keys(an_obj)); // will alert "2, 7, 100"
But as per the definition, key should be printed as 100, 2, 7 in the order they have been inserted in the object, instead of 2, 7, 100.
Please let me know, how the ordering of key happens in Object.key.
I think you might have misunderstood this:
The ordering of the properties is the same as that given by looping over the properties of the object manually.
What this means is that the order of the properties in Object.keys is the same as if you did a for-in loop.
Compare the results of these:
var an_obj = { 100: "a", 2: "b", 7: "c"};
//using object.keys...
console.log(Object.keys(an_obj));
//using a manual loop...
for(var k in an_obj) { console.log(k); }
You will find the order for both these is the same.
JavaScript objects are unordered key-value pairs. Object.keys returns an array of the keys of the object in the order they would be returned if you were to iterate over them, but it makes no guarantees over the order of the result in relation to the order of insertion.
Objects are by definition (See specification: http://www.ecma-international.org/publications/standards/Ecma-262.htm ) unordered. So no matter how you did the input, there is no guarantee of the order of the keys. If you wish to maintain the order, you should keep a seperate list with the order of the keys.
I am explaining a bit more about the difference between these :
Object.keys(obj)
for(var key in obj){
console.log(key);
}
Similarity :
Both returns keys in same order. Not a single difference between these.
Explanation:
If you have numeric keys in your object then
All numeric keys comes in natural ordering.
All other keys comes in insertion order.
If object does not contain any numeric key then insertion order will be followed by both the tricks.
Example:
var sec_obj = {0:"0", "d":23, "r": "a", "a": "b", "7": "c","z":23, 23:23};
//using object.keys...
console.log(Object.keys(sec_obj));
//using a manual loop...
for(var k in sec_obj) { console.log(k); }
Result
["0", "7", "23", "d", "r", "a", "z"]
0
7
23
d
r
a
z
It’s important to mention the limitations of Object.keys, as MDN article does. It recommends to use getOwnPropertyNames. MDN articles also show browser support.
Can anyone explain why the second alert says 0 ?
var pollData = new Array();
pollData['pollType'] = 2;
alert(pollData['pollType']); // This prints 2
alert(pollData.length); // This prints 0 ??
The length of the array is only changed when you add numeric indexes. For example,
pollData["randomString"] = 23;
has no effect on length, but
var pollData = [];
pollData["45"] = "Hello";
pollData.length; // 46
changes the length to 46. Note that it doesn't matter if the key was a number or a string, as long as it is a numeric integer.
Besides, you are not supposed to use arrays in this manner. Consider it more of a side effect, since arrays are objects too, and in JavaScript any object can hold arbitrary keys as strings.
Because you haven't put anything into the array yet. You've only been assigning to a dynamically-created pollType attribute on the array object.
If you use numeric indices, then the array automagically takes care of length. For example:
var arr = [ ]; // same as new Array()
arr[2] = 'Banana!';
alert(arr.length); // prints 3 (indexes 0 through 2 were created)
The length property takes into consideration only those members of the array which names are indexes (like '1', '2', '3', ... ).
Arrays in JavaScript have numeric indexes only.
Use an object, which is essentially what you are doing above, setting properties on that array object.
array.length returns how many values are stored in the array. The first alert is returning the value of the position 'pollType'.
The reference guide I always use when needing help with javascript arrays is this page http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
I'd also read what it says under the heading Javascript Does Not Support Associative Arrays, as you may run into problems with this also.
var pollData = Array();
function test() {
pollData[0] = 2
alert(pollData[0]);
alert(pollData.length);
}
//[x] is the array position; hence ['polltype'] is causing issues