how can i access properties of an object - javascript

i have an array of objects and i want to return the 'message' property of each of the objects.
i got the objects by calling my own oModel.oData which i created. now that i have these 5 objects how can i get the "message" property from these 5?
also, is there a way to count the number of objects i have in total? e.g sum of oModel.oData objects?
*note the objects are inside an array.
Thank you in advance :)

You can use .length to count your objects inside an array. YourArray.length this will return the numbers of element (in your case the object) inside the array.
As for the message you will need to loop each object inside of your array. you can easily do that using JQuery library https://jquery.com/
It will look like this
$(function(){
$.each(YourArray,function(i){
console.log(YourArray[i].message);
});
});
Or in javascript
for (var i = 0; i < YourArray.length; i++) {
console.log(YourArray[i].details);
};

If it's an array, you can simply do array.length to get the total number of objects.
As for getting the message from each of them, you'd simply have to loop over the array like :
array.forEach(function(obj) {
console.log(obj.message)
});
Let me know if you have any more questions.

Method 1:
for (var i = 0; i < oModel.oData.length; i++) {
console.log(oModel.oData[i].message);
}
Method 2:
(oModel.oData).forEach(function (obj) {
console.log(obj.message);
});
to get your objects length:
var _len = oModel.oData.length;
console.log(_len);
You can read more about arrays here.

Related

Array Says Its Length Is 0 But Console Says Otherwise

Good Afternoon,
I have encountered a problem with my code:
I have a for function adding values to an array variable but whenever I run the page it gives me an error stating that the array is empty. Here's the code adding values to the array:
if(this.Type === "Image") {
this.Frames = [];
for(var i = 0; i <= Sources.length - 1; i++) {
var Img = new Image();
Img.src = Sources[i];
this.Frames["Frame" = i] = Img;
}
} else {
this.Frames = [];
for(var i = 0; i <= Sources.length - 1; i++) {
this.Frames["Frame" + i] = Sources[i];
}
}
The code runs fine. How do I know that? Well I went on the JavaScript console and checked what value the array had. It said Frames[0], but when I collapsed it, it had Frame0, and when I collapsed that, the source it had was the correct source. So, what is going on with this? Is it a glitch or am I doing something wrong that I didn't know of before?
Thanks in advance.
That's because JavaScript only has numeric arrays. It does not have associative arrays.
When you do: this.Frames["Frame" + i] = Sources[i];, what you are doing is adding a property to the array (in JavaScript, everything is an object, and can therefore have properties). You are not actually pushing to the array.
One thing you can do is use an object instead: this.Frames = {};.
Or, you can .push() onto the array and use it as a numeric array.
this.Frames[i] = Sources[i];
// or
this.Frames.push(Sources[i]);
The .length property of JavaScript arrays only counts properties whose names are strings that look like integers (like "0", "1", etc). You can add whatever properties you want to an array instance, but only numeric properties affect the length of the array.

How to access multidimensional array by index in javascript?

I have an array like below in java-script
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
]
I tried accessing the individual values and was able to by the below code
alert(Result[0].ID) or alert(Result[0].Phase)
Is there a way to access this by index? like Result[0][1], i tried but getting [object][object]
also i need to access column count
Please help me
You have array of object and by using for loop you can easily access all element value.
try following
function getValue() {
var keys ;
var Result = [{"ID":1,"Type":"Pyramid","Phase":"One"}, {"ID":2,"Type":"Pyramid","Phase":"Two"}]
for(var i=0; i<Result.length;i++){
keys = [];
for(var k in Result[i]){
keys.push(k);
}
for(var k=0;k<keys.length;k++){
console.log(keys[k]+"="+ Result[i][keys[k]]);
}
console.log("key count =" +keys.length);
}
}
CHECK THIS
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
alert(Result[0][Object.keys(Result[0])[0]]);
Result[0] gets the first row
Object.keys(Result[0]) gets the keys in the first row
Object.keys(Result[0])[0] gets the first column name.
Object.keys(Result[0]).length is the column count in the first row.
Also, objects are not indexed based on a linear integer index as arrays are, so assigning ordered numbers to the unordered list of keys is not right.
A two dimensional array would look like this:
Result = [
[1,"Pyramid","One"],
{2,"Pyramid","Two"}
]
in this case, you could address each field like so: Result[row][col] thus Result[0][2] would yield One.
To access fields in an array of object use the syntax you have provided. Also, why would you want to access the fields in your objects based on id? Or why would you not use an array of arrays?
Your Result is an array of object, then you must first get an object, and then get the property of your object. This is not a multidimensional array.
You array has an object we have to convert that object to array. So converting whole var Result to newResult you can access newResult and it's component through index number
Result = [
{"ID":1,"Type":"Pyramid","Phase":"One"},
{"ID":2,"Type":"Pyramid","Phase":"Two"}
];
var newResult = [];
for (var i = 0; i < Result.length; i++) {
newResult[i] = [];
for (var x in Result[i]) {
if (Result[i].hasOwnProperty(x)) {
newResult[i].push(Result[i][x]);
}
};
};
console.log(newResult);
Use newResult instead of Result
You can get ID by newResult[0][0]
http://jsfiddle.net/LLz1cbok/

how to get array values of keys stored in an object with "for in" loop in javascript [duplicate]

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
In Javascript, I'd like to have an object with three properties, "zone1", "zone2", "zone3", each of which store an array of place names. I would like to search for a match by iterating through the arrays to find a place name.
The following questions almost gets me there, but don't work for me because I am not using jQuery, and I want the value, not the key:
Performing a foreach over an associative array of associative arrays
Getting a list of associative array keys
My code looks like this:
var zoneArray = {};
zoneArray["zone1"] = ["placeA", "placeB"];
zoneArray["zone2"] = ["placeC", "placeD"];
function getZone(place, zoneArray) {
var zone;
for (var key in zoneArray) {
for(i = 0; i<key.length; i++) {
if(key[i] == place) {
zone = key;
return zone;
}
}
}
}
getZone("placeC", climateZoneArray);
Apparently however, "key[i]" is referring to letters of the zone names, like, "z" "o" "n" "e"
Could anybody please help me understand or best handle this situation in Javascript?
Use zoneArray[key] to access the array.
for (var key in zoneArray) {
var arr = zoneArray[key]
for(i = 0; i<arr.length; i++) {
if(arr[i] == place) {
zone = key;
return zone;
}
}
}
Using for ... in to iterate over an object's properties can lead to some pretty surprising results, especially if you're working in an environment where Object.prototype has been extended. This is because for ... in will iterate over an objects enumerable properties and the enumerable properties contained in that objects prototype chain. If this isn't what you want but you are going to use for ... in anyways, it's recommended to have a conditional statement at the top of the loop that checks that the property belongs to the object which is being iterated over. (if (!foo.hasOwnProperty(x)) continue;). Luckily, there is Object.keys(). You can use Object.keys() to get an array of an objects own enumerable properties, if you do this you can skip hasOwnProperty ugliness. Instead of iterating over the object you can iterate over an array of it's keys.
var collection = {
zone1: ['placeA', 'placeB'],
zone2: ['placeC', 'placeD']
};
function getZone(needle, collection) {
var zones = Object.keys(collection),
found;
for (var i = 0, l = zones.length; i < l; i++) {
found = collection[zones[i]].filter(function(place) {
return needle == place;
});
if (found.length > 0) {
return zones[i];
}
}
};
console.log(getZone('placeC', collection));
This is also here on jsfiddle.net
One last thing, be very careful when creating variables, in the inner for loop you created the variable i without using the var keyword. This resulted in i being bound to the global context, something you really want to avoid.

Iterate over a collection of objects in javascript and return true from that function

I have an object called collection, and I want to test to see if justin is part of this collection.
collection = { 0:{screen_name:"justin"},1:{screen_name:"barry"}}
I'm trying to discover the most efficient method, to pass in a name to function called present_user(user), to see if the user is part of the collection and I'm kind of stumped.
So my collection is built up of objects 0, 1, n+1. I'm trying to iterate through this collection. So far I only test [0]
function present_user(user) {
collection[0]["screen_name"] == user -> return true in the case of "justin"
}
How can I iterate over all values of this collection, and return true if the user_name "justin" is passed into a function?
Your collection is an object and not an array, so this would be a way to do it:
var present_user = function(user){
for (var k in collection) {
if (collection[k]['screen_name'] == user) return true;
}
return false;
};
If your outer object keys are all numbers, you should be using an array instead:
var collection = [{screen_name:"justin"}, {screen_name:"barry"}];
Then iterate with:
function present_user(user) {
for(var i=0; i < collection.length; i++) {
if(collection[i].screen_name === user) return true;
}
}
You could loop the object collection too (with for..in, see mVChr's answer), but in this case it looks like you really should be using an array.
You could also turn a collection or object into an array, so that you could use array methods to iterate:
Object.values(collectionOrObject);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
This especially comes in handy when you use the native javascript dom selectors like:
document.getElementsByClassName('someClass');
Which returns a collection
If you know how many objects are in the collection ahead of time, you can use add a length property and use
Array.prototype.some.call(collection, function (elem) {
return elem.screen_name = 'justin';
});
Ideally collection would be an array initially so you could just use collection.some, but I understand that may not be possible.
If you have no way of knowing the length ahead of time in that case, you have to iterate manually. Sorry.
var exists = false, i;
for (i in collection) {
if (collection.hasOwnProperty(i)) {
/* may also want to check `screen_name` property existence
if (collection[i].screen_name == 'justin') {
exists = true;
break;
}
}
}
function any(user) {
return collection.filter(function (item) { return item == user }).length > 0;
}
The only "gotcha" here is that you need to have an array here not an object, if you have no problem modifying the collection variable to array, this functional approach would be the most elegant one, in my opinion.
One more thing to take under consideration though is that this code will not stop the moment it finds the first match, it will test all the items in array instead so I would recommend using it only if the array is not large.

Javascript / JQuery - How do I find the size of this array of objects?

I have this code to iterate through an array of objects:
for (vehicleIndex in scenes[sceneID].vehicles) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
...
}
but I need to know how to determine the number of items being iterated through so that on the final item, I can execute a particular function. How do I do this?
Example in ES5:
Object.keys( scenes[sceneID].vehicles ).forEach(function( vehicle, index, arr ) {
if( index === arr.length - 1 ) {
// do something on last entry
}
});
Even tho, "last" just means the last element which was looped over. Since there is specific order within a Javascript object (they are infact unordered). However, we could sort the object key names manually by just chaining a .sort() before the .forEach()
var arraySize = scenes[sceneID].vehicles.length;
var i;
var currentItem;
for (i = 0; i < arraySize; i++) {
currentItem = scenes[sceneID].vehicles[i];
if (i == arraySize - 1) {
// do something special
} else {
// do something not so special ;-)
}
}
scenes[sceneID].vehicles should have a length property.
for (vehicleIndex in scenes[sceneID].vehicles) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
...
}
doSomethingWithLastItem(vehicleId);
Because JS does not have block scope, by the time your loop finished vehicleId will be the last item's id.
In generic terms you can get the size of an array by accessing the .length property. You can also get the size of an object using Object.keys(obj).length.
Use this to find the length:
scenes[sceneID].vehicles.length
length is a built-in property in arrays. However, if you want to check for the last item, you have to check
scenes[sceneID].vehicles.length - 1
as arrays are zero-indexed.
Also, you should not use for...in to loop on arrays - if someone extends Array.prototype (or worse, Object.prototype), then you will not be happy. Use a normal for loop (which also allows you to use the final item easily):
var len = scenes[sceneID].vehicles.length;
for (var vehicleIndex = 0; vehicleIndex < len; vehicleIndex++) {
vehicleID = scenes[sceneID].vehicles[vehicleIndex];
//...
}
//Do something with the final item here
//Similar to this: itemFunc(vehicleID);
See this SO question for more details.

Categories