Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch array keys with jQuery?

Tags:

arrays

jquery

key

Good afternoon. I have an array with some keys, and values in them. I then need to fetch the array keys and not the data in them. I want to do this with jQuery. I know for example that PHP has a function called array_keys(); which takes the array as a parameter and gives you an array back with each key in each index.

This is what I came up with, and it works... the only problem is that it seems so unefficent;

var foo = []; foo['alfa'] = "first item"; foo['beta'] = "second item";  for (var key in foo) {     console.log(key); } 

This will output;

alfa beta 

But is there any predefined function for this, as in PHP or any other more effective way of getting this?

like image 432
Stefan Konno Avatar asked Aug 10 '09 10:08

Stefan Konno


People also ask

What is keys() in JavaScript?

keys() Method: The Object. keys() method is used to return an array whose elements are strings corresponding to the enumerable properties found directly upon an object. The ordering of the properties is the same as that given by the object manually in a loop is applied to the properties.

What is keys in array?

The array. keys() method is used to return a new array iterator which contains the keys for each index in the given input array. Syntax: array.keys() Parameters: This method does not accept any parameters. Return Values: It returns a new array iterator.

How do you access an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };


2 Answers

you can use the each function:

var a = {}; a['alfa'] = 0; a['beta'] = 1; $.each(a, function(key, value) {       alert(key) }); 

it has several nice shortcuts/tricks: check the gory details here

like image 159
dfa Avatar answered Sep 22 '22 13:09

dfa


Using jQuery, easiest way to get array of keys from object is following:

$.map(obj, function(element,index) {return index}) 

In your case, it will return this array: ["alfa", "beta"]

like image 36
dugokontov Avatar answered Sep 23 '22 13:09

dugokontov