is there any function to get the keys of an array using javascript
Also i want to reverse and array
eg:
appz_variable['412cc16e']="ABXZ";
appz_variable['axecr6fd']="YCSET";
I want the array indexes or keys in reverse order
I assume here you're talking about an object which some label (albeit incorrectly) an "associative array". For that situation, use a for...in loop to enumerate the object, like this:
for(var key in myObject) {
if(myObject.hasOwnProperty(key)) {
alert("Key: " + key + ", Value: " + myObject[key]);
}
}
For a normal array you just loop though based on an index, like this:
for(var i=0; i<myArray.length; i++) {
alert("Position: " + i + ", Value: " + myArray[i]);
}
The second is iterating over the array, while the first is enumerating the object...you shouldn't use a for...in loop on a normal array for example, as there are many problems that can arise.
You can index your array by numbers when it is created. perhaps like this:
appz_variable[0]['412cc16e']="ABXZ";
appz_variable[1]['axecr6fd']="YCSET";
and then you will have an "order" which you can then reverse...
Related
I am reading the book "JavaScript for web designers" and I've come to this example:
var fullName = {
"first": "John",
"last": "Smith"
};
for (var name in fullName) {
console.log(name + ": " + fullName[name]);
}
The output is:
"first: John"
"last: Smith"
What I don't get is: where do I tell the program to get the string "first" and "last". I mean, cycling the object "fullName", I fail to see how "name" can be related to "first" and "last". I hope this is clear.
Can you help? Many thanks!
for..in iterates over the keys of an object. You can then access an objects values by name using brackets.
var obj = {
a: 1,
b: 2,
c: 3
};
for (var key in obj) {
console.log('Key:', key);
console.log('obj[key] == obj["' + key + '"] == obj.' + key);
console.log('obj.' + key + ' == ' + obj[key]);
}
It's pretty simple to learn and/or understand. You're looping through all of the properties in the object fullName. For each property, you're giving it the temporary name/alias of name
So you could change it to for (var anything in fullName) and then in the body of the for loop you would reference each property by the name anything like so:
for (var anything in fullName) {
// anything is an alias for the current property your on of the object you're looping through
console.log(anything + ": " + fullName[anything]);
}
A for..in loop will iterate through the object's keys. If you use this on an array, then it (most browser engines) will convert the array into an object behind the scenes (read more on Dictionary Mode) and iterate the keys.
You can view the keys by using
var fullName = {
"first": "John",
"last": "Smith"
};
console.log(Object.keys(fullName));
And essentially the result of this call is then iterated. Keep in mind that using for..in does not guarantee order of the key value pairs.
in the above code name represent key of the object,
first and last are both keys in the object. and can be used to access the value in the object.
like in the first run of the loop it will be something like this
for("first" in fullName) {
console.log("first" + ": " + fullName["first"] //John);
}
When you loop through an object, you iterate through the keys. The keys of this object are first and last. Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in for more information.
I have a data which goes something like this
var data = [{"empid":1},{"empid":2},{"empid":3},{"empid":4},{"empid":5},{"empid":6},{"empid":7},{"empid":8},{"empid":9}]
when I try to iterate over it using Javascript, the value which is returned is another object.
I am trying to do something like this
for (var key in data) {
console.log(' name=' + key + ' value=' + data[key]);
}
I expected to see my empid values as part of 'value' in the log but the 'value' is another object array.
fiddle: http://jsfiddle.net/sourabhtewari/b6b3qxo7/
Note: I cannot use property name to fetch the value as the data would be dynamic. So I cant do something like JSON.stringify(data[key].empid)
You need to iterate over the array, and you don't do that with for..in, but with a regular for-loop, inside which you may use for..in because each array item is an object:
for (var i=0; i<data.length; i++) {
for (var key in data[i]) {
console.log(' name=' + key + ' value=' + data[i][key]);
}
}
Just call the property of it.
data[key].empid
See here a working example.
It's because you're converting an Object to a string, if you just call the empid property you'll see the value:
for (var key in data) {
console.log(' name=' + key + ' value=' + data[key].empid);
}
You can also use other functions to iterate on arrays though, with map you can retrieve your properties and store them in another array:
values = data.map( function(element) {
return element.empid;
}
// values will be an array with all the empid properties
Or Array.forEach():
data.forEach(function (element) {
console.log(element.empid);
}
Because it's an array and it's numeric, you could look at your code as such:
var data = [{"empid":1},{"empid":2},{"empid":3},...];
var data = {0: {"empid":1}, 1:{"empid":2}, {"empid":3}, ...}
When using a for...in loop, you are actually assigning the numerical value to your key, looping through all keys, but thats not what you want. When you ask for the value in that circumstance, you will get back the object assigned to that key! There are two ways you can do this. First, by modifying your code:
for (var key in data) {
console.log(' name=' + key + ' value=' + data[key].empid);
}
Or by using the proper way to loop through an array using a regular for loop:
for (var i = 0; o < data.length; i++) {
console.log(' name=' + i + ' value=' + data[i].empid);
}
You should never use for in for arrays, that iterates over object properties.
Use
for (var i = 0; i < data.length; i++) {
// ..
}
instead. You can access the value will in the loop as data[i].empid.
I have the next code:
var allFilesName = fs.readdirSync("./0/0");
console.log(allFilesName);
for (var i in allFilesName) {
console.log("the num is: " + i + " in: " + allFilesName);
The output is:
[ '6', 'd' ]
the num is: 0 in: 6,d
Why it get 0, when the allFilesName contains only 6 and d?
i = the index of element in array. if you want the element itself - use that:
console.log("the num is: " + allFilesName[i] + " in: " + allFilesName);
for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important. My Ref.
Try to work with the regular for loop it worked fine with me
var allFilesName = [ '6', 'd' ];
for (var i=0; i <= allFilesName.length; i++)
{
console.log("the num is: " + i + " in: " + allFilesName);
}
I have an array like this
var cons=Array();
cons[random_text]=random_number;
cons[random_text]=random_number;
...
I want to list all values in cons variable.How can I do this in one loop ?
There are no associative arrays in javascript, the index can be only numbers.
What you're creating is an object with key/value pairs, unless random_text for some reason actually is an integer, which would seem strange.
var cons = {}; // object, not array
cons[random_text] = random_number;
cons[random_text] = random_number;
// iterate
for (var key in cons) {
var value = cons[key];
console.log(key + ' : ' + value);
}
to get an array of the keys in modern browsers, there's also
var key_arr = Object.keys(cons);
for (var key in validation_messages) {
var obj = validation_messages[key];
for (var prop in obj) {
if(obj.hasOwnProperty(prop)){
alert(prop + " = " + obj[prop]);
}
}
}
This is the for loop that i have but i'm getting the response in ascending order. But i need it in descending order. Can some one help me.
Thanks
Javascript does not guarantee a specific object property order, see this: Does JavaScript Guarantee Object Property Order?
If you need a specific order, you should use an array.
If you had them in an array, the code would look like this(fiddle:http://jsfiddle.net/DH3VQ/1/) :
var props = [
{ key:"p1", value:"a"},
{ key:"p2", value:"b"},
{ key:"p3", value:"c"},
];
for (var i = 0; i< props.length; i++){
alert(props[i].key + " = " + props[i].value);
}
Or you could do something fancier:
props.forEach(function(prop){alert(prop.key + " = " + prop.value)});
But the standard for is probably more portable.
Like this:
Object.keys(validation_messages)
.sort(function(a,b) {
return b.localeCompare(a);
})
.forEach(function(key) {
var val = validation_messages[key];
console.log(key, val);
});
Object.keys gets the enumerable properties of an object into an Array. Then the .sort() will sort them in descending order, and the .forEach() will iterate the sorted set of keys.
So then for each key, you can grab the value from the object, and use it.