How to get array keys in Javascript?

Related searches

I have an array created with this code:

var widthRange = new Array();
widthRange[46] = { min:0,  max:52 };
widthRange[66] = { min:52, max:70 };
widthRange[90] = { min:70, max:94 };

I want to get each of the values 46, 66, 90 in a loop. I tried for (var key in widthRange) but this gives me a whole bunch of extra properties (I assume they are functions on the object). I can't use a regular for loop since the values are not sequential.

You need to call the hasOwnProperty function to check whether the property is actually defined on the object itself (as opposed to its prototype), like this:

for (var key in widthRange) {
    if (key === 'length' || !widthRange.hasOwnProperty(key)) continue;
    var value = widthRange[key];

Note that you need a separate check for length. However, you shouldn't be using an array here at all; you should use a regular object. All Javascript objects function as associative arrays.

For example:

var widthRange = { };  //Or new Object()
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

Array.prototype.keys(), All Javascript objects function as associative arrays. The stringified keys can be queried with Object. keys(array) . Retrieve all the names of the object's properties. The keys() method returns an Array Iterator object with the keys of an array. Note: this method does not change the original array.

The stringified keys can be queried with Object.keys(array).

Object.keys(), Below is the example of the Array keys() method. Example: filter_none. <script> // Taking input as an array A. // containing some elements. var A = [ 5, 6, 10 ]; // array.keys() method is called. var iterator = A.keys(); // printing index array using the iterator. for (let key of iterator) { Output: 0 1 2. How to get a list of associative array keys in JavaScript ? filter_none edit close play_arrow link brightness_4 code. Method 2: Using Object.keys () function: The Object.keys () is edit close. play_arrow. link brightness_4 code. Method 2: Using Object.keys () function: The Object.keys () is an

If you are doing any kind of array/collection manipulation or inspection I highly recommend using Underscore.js. It's small, well-tested and will save you days/weeks/years of javascript headache. Here is its keys function:


Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

How to get array keys in Javascript?, Object.keys to get the keys, using parseInt to cast them as numbers. filter to get only ones you want. map to build an array from the original object of just the indices you're after, since Object.keys loses the object values. Debug: console.log(widthRange) console.log(relevantKeys) console.log(relevantValues)

Say your array looked like arr = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 }, { a: 7, b: 8, c: 9 } ] (or possibly other keys) you could do => {
    return Object.keys(o)
}).reduce((prev, curr) => {
    return prev.concat(curr)
}).filter((col, i, array) => {
    return array.indexOf(col) === i

["a", "b", "c"]

JavaScript Array keys() Method, We will push some student details in it using javascript array push. We will verify these changes by looping over the array again and printing the result. Basically we will use javascript array get key value pair method. 1. Using an empty JavaScript key value array. 2.

for (var i = 0; i < widthRange.length; ++i) {
  if (widthRange[i] != null) {
    // do something

You can't really get just the keys you've set because that's not how an Array works. Once you set element 46, you also have 0 through 45 set too (though they're null).

You could always have two arrays:

var widthRange = [], widths = [], newVal = function(n) {
  return n;
widthRange[newVal(26)] = { whatever: "hello there" };

for (var i = 0; i < widths.length; ++i) {

edit well it may be that I'm all wet here ...

Input : var object = { 0: 'x', 1: 'y', 2: 'z' }; console.log(Object.keys(object)); Output : ['0', '1', '2'] Explanation : In this example, an array like object “check” has three property values { 0: ‘x’, 1: ‘y’, 2: ‘z’ } and the object.keys() method returns the enumerable properties of this array. The ordering of the properties is the same as that given by the object manually.

The Object.keys () method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. JavaScript Demo: Object.keys ()

Array; Plain objects also support similar methods, but the syntax is a bit different. Object.keys, values, entries. For plain objects, the following methods are available: Object.keys(obj) – returns an array of keys. Object.values(obj) – returns an array of values. Object.entries(obj) – returns an array of [key, value] pairs.

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John:

  • It looks like you have data which, while it happens to have numeric keys, isn't actually array data. I'd look at using a regular object here.
  • @Quentin It's called a sparse array. Performance-wise, it's best to use an array instead of an object here. Also, performance-wise, the best answer is not even listed: Array.prototype.forEach. Calling Object.keys on an array is illperformant because browsers don't optimize for it. for(var key in array) is bad because it traverses the prototype and stringifies each number key it encounters (converting doubles to base10 is very slow). forEach, however, was designed exactly for the purpose of iterating sparse arrays and will give your code excellent performance compared to other solutions
  • Really? Wow I learn something every day here, and so often it's from you SLaks :-) I am surprised that Array keeps track of its explicitly-set indexes like that. Maybe I shouldn't be.
  • @SLaks: Thanks, changing it to an object seems the nicest solution. One more question: is there a way to iterate in reverse order?
  • No; you'll need to do it yourself.
  • Why do you need a separate check for length? Isn't is marked as [[DontEnum]] in all browsers?
  • @Roatin: I don't know. Better safe than sorry.
  • This returns the keys as strings, not numbers, just so everyone is aware.
  • The best solution... TY
  • Made my day! :D <3 This solved it where array.keys() returned nothing.
  • Arrays only keep track of length, they don't go through and create however many objects. Basically, when a new index is found it checks to see if that new index is greater than length...if it is that new index becomes the new length. Because of that it is possible to get only the indexes you defined with a for-in loop
  • I bet he's importing Prototype or something like that. In general, those "in" loops are risky.
  • Well I'm using jQuery but also Joomla which uses mootools, something is adding those properties.
  • Extending a prototype that you didn't create is a very bad idea, no matter how convenient you think it is.