For.. in loop - why does it work? - javascript

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.

Related

Efficient way to find name value pairs from JSON array in Javascript

I am currently making a call to a service which sends a response as an array of objects with name value pairs. An example of this can be seen below. There could be any amount of these name value pairs in any order but I just want to access the value for the name "name2". Is there an efficient way other than looping through each object and checking the name to obtain the corresponding value for name2?
[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}]
So from the above data set I would want an efficient way to search for name2 and get the corresponding value "value2".
Thanks
Unless you know the specific index of the object with the name name2 no.
You'll need to iterate until you find that name then you can bail out.
e.g.
var jsonData = [{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}];
for(var i=0;i<jsonData.length;i++){
if(jsonData[i]['name'] == 'name2'){
console.log('The value is: ' + jsonData[i]['value']);
break;
}
}
Note that if you don't need to support Internet Explorer, you can use the Array.find() method to simplify this.
if you don't want to iterate over the array manually you can use lambda expression as the following
a =[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}] ;
//get the items that match your criteria
a.filter(item=>item.name=="name2")
//get those items' values
a.filter(item=>item.name=="name2").map(item=>item.value)
//get the first value (if you know that it's only one item that will match)
a.filter(item=>item.name=="name2").map(item=>item.value)[0]
You can use Array#find method.
var arr = [{
"name": "name1",
"value": "value1"
}, {
"name": "name2",
"value": "value2"
}];
// get the object containing name as `name2`
var obj = arr.find(function(v) {
return v.name === 'name2';
});
// get value property if object is defined
var res = obj && obj.value;
console.log(res)

Displaying all keys value pair of array in nested json javascript

I have a JSON data from a URL and c am consuming it using jQuery ajax method.
Now as the JSON code below shows I have a DATA array containing objects in my JSON, now if I access FirstName using resp.DATA[0].FirstName, I am able to get it, but now I have to display all the key value pairs in DATA array and i don't know the key name i.e. I have to show every key and value.
There are two customers on data.
How can I do it either using JavaScript or jQuery?
JSON DATA:
{
"ERROR": [],
"DATA": [{
"CustomerID": "124",
"BranchID": "12",
"FirstName": "sandeep",
"LastName": "b",
"EmailID": "gggg#gmail.com",
"Sex": "Male",
"Landline": "",
"AlternateNumber": "",
"Password": "5735c2801",
"USERVARCHAR_2": ""
}],
"META": {
"totalPages": "1",
}
}
I have to display Key and value of each customer data in the form KEY:VALUE, so please suggest me how to loop this.
Use the for loop to iterate over javascript array literal
for (var key in resp.DATA) {
// skip loop if the property is from prototype
if (!resp.DATA.hasOwnProperty(key)) continue;
var objct = resp.DATA[key];
for (var prop in objct) {
// skip loop if the property is from prototype
if(!objct.hasOwnProperty(prop)) continue;
// your code
alert("The key is "+prop + "and the value is " + objct[prop]);
}
}
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Use Object.keys(object_name) to fetch all the keys of a Object.
The Object.keys() method returns an array of a given object's own
enumerable properties, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
for(var cust of resp.DATA){ // To iterate a array
for(var key in cust){ // To iterate a object ennumerable properties
console.log("Key is: "+key+" and Value is: "+cust[key]);
}
}
do this:
$(resp.DATA[0]).each(function(key, value){
// your code
});
Loop in to your array like this using .each()
$.each(your_array, function(key, value) {
alert('Array Key is: '+ key + ' \n Array Key value is: ' + value);
});
.each() Iterate over a jQuery object, executing a function for
each matched element.

Working with associative arrays in javascript

I want to use a variable as index of my associative array
var usersName = []; // Just defining
userName[socket.id] = socket.name; // socket.id is an alphanumeric string
I want to use that socket.id(string) as the custom index of usersName array, so I can get a list of all the users connected to the socket. The problem is the way I'm escaping the variable ( I guess).
I've tried this but didn't work:
usersName ['\''+socket.id+'\''] = socket.name;
This works in PHP but, I just can't get it to work in javascript
Thanks for the help.
What you are trying to do is essentially this:
// say socket = {id: 123, name: 'Bob'};
var foo = {}; // create an object
foo[socket.id] = socket.name; // put socket.name under foo.
var i;
for (i in foo) { //loop through list
console.log(i, "is", foo[i]); //123 is Bob
}
right? Like the comments posted, JS doesn't have "associative arrays" but instead something better- psuedo-classical objects. Objects in JavaScript are nothing like those in PHP. You need to relearn what an "object" means when learning JavaScript. Arrays in javascript are not something to be proud of.. They are essentially just objects extending the Array prototype and with a special 'length' property. Arrays in JS also allow you to get data in order, by performing a for(i =..; i..; i +=..) loop. Other than the benefits of Array.prototype and the ability to load a list of things in some reliable order, arrays are not that special.
Hopefully this will work the way you want it. It's kind of PHP style:
1
var usersName = new Object();
usersName["123"] = 'Jane';
usersName["923"] = 'Charles';
for (var key in usersName) {
console.log(key + ' => ' + usersName[key]);
}
2
var usersName = {
'123' : 'Jane',
'923' : 'Charles'
};
for (var key in usersName) {
console.log(key + ' => ' + usersName[key]);
}

How to get the keys of an array using javascript?

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 print json data.

I have a json output array like this
{
"data": [
{
"name": "Ben Thorpe",
"id": "XXXXXXXXXXX"
},
{
"name": "Francis David",
"id": "XXXXXXXXXXX"
},
}
I want to loop through it and print out the all the names using javascript. I want to be able to do this.
for(i=0;i<length;i++){
var result += response.data[i].name + ', ';
}
But I am unable to find the length of the json object using javascript.
response.data is an array of objects, thus has a length property that you can use to iterate its elements.
var result;
for(var i=0;i<response.data.length;i++)
{
result += response.data[i].name + ', ';
}
If you just want to look at it for debugging purposes, do a console.log(myObject) or console.dir(myObject) and take a look at the firebug/chrome/safari console.
The object doesn't automatically have a length property because it's not an array. To iterate over properties of an object, do something like this:
for (var p in location) {
console.log(p + " : " + location[p]);
}
In some cases you may want to iterate over properties of the object, but not properties of the object's prototype. If you're getting unwanted stuff with the regular for..in loop, use Object.prototype's hasOwnProperty:
for (var p in location) if (location.hasOwnProperty(p)) {
console.log(p + " : " + location[p]);
}
The thing is, if this is/was really JSON data, it should have been a string at some point, as JSON is by definition a string representation of an object. So your question "How to print json data" almost reads like "How to print a string." If you want to print it out, you should be able to catch it before it gets to whatever parsed it into that object and just print it out.

Categories