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.
Related
I have an array of objects
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
I want to check against the object property and perform some sort of logic. I am new to JS so I'm not sure of all the methods I have access to. Basically I want to compare the key value of the object to a string. If the key and the string are the same, then I would remove that object from the array. I'm not sure how to iterate through the object's key in the array.
var str = "v1";
for (var i in j) {
if (i.key == str) { // not sure how to access key value
j.splice(i,1);
}
}
Try this :
var j = [{"v1":["1","2","3"]}, {"v2":["4","5","6"]}, {"v3":["7","8","9"]}];
for (var i = 0; i < j.length; i++)
{
for (var k in j[i]) //do use this if you need to iterate
{
if (k === "mySomething")
{
//...do your stuff
}
}
}
Edit
less verbose :
for (var i = 0; i < j.length; i++)
{
if ("mySomething" in j[i])
{
//...do your stuff
}
}
As we've been discussing in comments, there is seldom a reason to use an array of objects that each only have one property (unless you're using the array to maintain a specific order), so I thought perhaps your problem might be easier if the data was structured like this:
var j = {"v1":["1","2","3"], "v2":["4","5","6"], "v3":["7","8","9"]};
And, you could then iterate it like this:
for (var key in j) {
console.log("j[" + key + "] = ", j[key]);
}
Working demo: http://jsfiddle.net/jfriend00/qdgzso1g/
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.
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...
How to sort this object lexicographically by its keys:
var obj = {'somekey_B' : 'itsvalue', 'somekey_A' : 'itsvalue');
so that it outputs like this:
for (k in obj) {
alert(k + ' : ' + obj[k]); //first "somekey_A : itsvalue"; then "somekey_B : itsvalue"
}
You can't. The order in which for..in loops through the property names is implementation-specific and cannot be controlled. Your only alternative is to organize the properties yourself in some way, such as building an array of keys and then sorting it, e.g.:
var keys, index;
keys = [];
for (k in obj) {
keys.push(k);
}
keys.sort();
for (index = 0; in dex < keys.length; ++index) {
k = keys[index];
alert(k + ' : ' + obj[k]); //first "somekey_A : itsvalue"; then "somekey_B : itsvalue"
}
You could, of course, put that in a function on the object and use it to iterate through the keys. Alternately, you could keep a sorted array on the object itself, provided you kept it up-to-date when you created new properties.
You need to copy the keys of the object into a sortable data structure, sort it, and use that in your for..in loop to reference the values.
var ob = {
foo: "foo",
bar: "bar",
baz: "baz"
};
var keys = [];
for (key in ob) {
keys.push(key);
}
keys.sort();
keys.forEach(
function (key) {
alert(ob[key]);
}
);
If the object is an arrya (or you made it an array using Prototype, jQuery, etc) you can use the native array.sort() function. You can even use your own callback function for sorting the values.