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?
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.
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.
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' }] };
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
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With