Javascript object containing array of comma separated coordinates - javascript

What's the correct format for an object containing an array of comma separated numbers?
Here is what I am doing, but I am unsure if it is the correct way:
var myObj = {
'coord1' : { 'section-a' : [216,259,216,294,165,294,165,259,216,259] },
'coord2' : { 'section-a' : [20,218,8,178,3,143,6,112,13] }
};
I'd like to access the coordinates of a section by the following:
for(var coord in myObj){
for(var section in coord){
alert(section);
}
}
And have the raw coordinates returned as a comma separated string. Any suggestions?

Unfortunately for in loops don't do quite what you're expecting.
The variable that you create is property name of the current iteraton when you iterate over an object. It is the index of the array when you iterate over an array.
for(var prop in myObj){
for(var i in myObj[prop]){
alert(myObj[prop][i]);
}
}
Note, when iterating over objects you may only want to iterate on direct properties of that object, not properties up the protype chain. Use hasOwnPrototype if you only want to iterate over direct properties on the object.
for(var prop in myObj){
if(myObj.hasOwnProperty(prop)) {
for(var i in myObj[prop]){
if(myObj[prop].hasOwnProeprty(i)) {
alert(myObj[prop][i]);
}
}
}
}

Remember that a for in loop in javascript returns an objects property key not the object the key refers to. Also use .hasOwnProperty to avoid possibly looping over an objects prototype.
You would need to change it to:
for (var coord in myObj){
if(myObj.hasOwnProperty[coord]){
var coord = myObj[coord];
for(var section in coord)
if(coord.hasOwnProperty[section]){
alert(coord[section]);
}
}
}
}

Related

Search value in object

I have following object im not sure how to proceed.
Object image
How can I go through all objects and select the content array and search for a value x. And when the value x is in the object I need to get the object title from the object where the value was found.
Can anyone give me a hint how I can solve this problem?
you can use for...in to iterate over the object and indexOf() to check if a key exists in the array content. something like this:
function searchVal(x){
for(var key in obj){
if(obj[key].hasOwnProperty('content') && obj[key].content.includes(x))
return key;
}
}
You can use for...in to iterate the object keys, then a regular for loop to check the content array for your specific value:
function findTitle(x) {
for (var key in obj) {
for (var i = 0; i < obj[key].content.length; i++) {
if (obj[key].content[i] === x) {
return key;
}
}
}
}
let name = Object.values( obj /*your main object*/ )
.find( obj => obj.content.includes(x) )
.name;
You could find the first object in the Objects values of your main obj, that has a property content which includes x, then get the name of that object.

For loop is not working with json data

I'm trying to make a loop in javascript with the following code. It's getting length from json data.
The console.log(albums.data.length); line is working and returning 3. Why the loop is not working then?
The console.log(x); is not returning anything, even not blank line.
There is also no error in console.
function getBestPhoto(albums){
console.log(albums);
console.log(albums.data.length);
for(var x in albums.data.length){
console.log(x);
for(var y in albums.data[x].photos.length){
console.log(y);
}
}
}
I have tried another type of loop(for(var i = 0; i < blabla; i++)) but its not working too.
Edit:
I wanna use
for(var x = 0; x < albums.data.length; x++){
console.log(albums.data[x].photos.id);
}
instead of
for(var x in albums.data){
How can i do it?
You should remove .length from loops
function getBestPhoto(albums){
console.log(albums);
console.log(albums.data.length);
for(var i = 0; i < albums.data.length; i++){
var x = albums.data[i];
console.log(x);
for(var j = 0; j < albums.data[i].photos.length; j++){
var y = albums.data[i].photos[j];
console.log(y);
console.log(albums.data[i].photos[j].id);
}
}
}
The for-in loop is not for arrays, it is for iterating over properties/fields of an object. If albums.data is an array, you should use the forEach loop statement instead. If albums.data is an object, and you are trying to access its properties/fields/attributes, you can use the for-in construct.
If albums.data is an array, try:
albums.data.forEach(function(element, index) {
// Here you have access to each element (object) of the "albums.data" array
console.log(element.toString());
// You can also access each element's properties/fields if the element is an
// object.
// If the element is an array itself, you need to iterate over its elements
// in another inner foreach.
// Here we are accessing the "photos" property of each element - which itself
// is another array.
element.photos.forEach(function(photo, index) {
// Here you have access to the elements of the "photos" array
// Each element of the "photos" array is put in the photo variable.
// Assuming each element of the "photos" array is an object, you can access
// its properties, using the dot notation:
console.log("photo id=", photo.id);
// If the property name (e.g. "id") is not a valid javascript name
// (has some special symbols), use the bracket notation
console.log("photo URL=", photo["photo-url"]);
});
});
You can also use the lodash library for this (and many other neat functionalities).
If albums.data is an object, try:
for (var prop in albums.data) {
// Again, this construct is for accessing properties of an object
// (e.g. if albums.data is an object), not an array.
console.log("property name=" + prop + ", " + "property value=" +
albums.data[prop]);
}

Accessing properties of a variable object with JavaScript

I have a js object that looks like this:
var object = {
"divisions": {
"ocd-division/country:us": {
"name": "United States",
}
}
};
I want to access the property listed under the nested object "ocd-division/country:us" (aka "name"), but the problem I'm having is that "ocd-division/country" is a variable object. Like it might be ":can" for Canada or something.
My question is, can I still access the name property under that object even though it's variable? I wrote the code I came up with below, but it calls the object literally, so it can't account for a change in the object's name.
var country = document.getElementById("p");
p.innerHTML = object.divisions["ocd-division/country:us"].name;
I'm new to JavaScript so I'm sorry if this is a dumb question.
When you don't know the properties of an object, you can use
for...in loop
It iterates enumerable own and enumerable inherited properties.
Object.keys
It returns an array which contains enumerable own properties.
Object.getOwnPropertyNames
It returns an array which contains own properties.
// Adding properties: "ownEnumerable", "ownNonEnumerable",
// "inheritedEnumerable" and "inheritedNonEnumerable"
var obj = Object.defineProperties({}, {
ownEnumerable: {enumerable: true},
ownNonEnumerable: {},
});
Object.defineProperties(Object.prototype, {
inheritedEnumerable: {enumerable: true},
inheritedNonEnumerable: {},
});
// Display results
function log(id, arr) {
document.getElementById(id).textContent = '[' + arr.join(', ') + ']';
}
log('forin', function(forInProps){
for (var prop in obj) forInProps.push(prop);
return forInProps;
}([]));
log('keys', Object.keys(obj));
log('names', Object.getOwnPropertyNames(obj));
<dl>
<dt><code>for...in</code></dt><dd id="forin"></dd>
<dt><code>Object.keys</code></dt><dd id="keys"></dd>
<dt><code>Object.getOwnPropertyNames</code></dt><dd id="names"></dd>
</dl>
object.divisions[Object.keys(object.divisions)[0]].name
Sure...
for (var division in object.divisions) {
var name = object.divisions[division].name;
// Do what you want with name here
}
If the object has prototype methods you will want to use Object.prototype.hasOwnProperty() to ensure they don't get iterated like so:
for (var division in object.divisions) {
if (!object.divisions.hasOwnProperty(division)) continue;
var name = object.divisions[division].name;
// Do what you want with name here
}
Or use Object.keys() if you don't care about IE8 support and iterate over those.
Object.keys(object.divisions).forEach(function(division) {
var name = object.divisions[division].name;
// Do what you want with name here
});
EDIT: Upon re-reading your question it occurs to me that you may already know the key name but want to access the object with a variable key name, which is also absolutely fine:
var division = 'ocd-division/country:us';
object.divisions[division].name;
When using [] bracket notation to access an object you can insert any code that evaluates to a string, you could even call a function in there that returns a string.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
You can iterate through object using for loop.
var obj = {
"divisions":{
"ocd-division/country:us":{
"name" : "United States"
}
}
}
Here is the for loop
for(var a in obj){ //loop first the object
for(var b in obj[a]){ // then second object (divisions)
for(var c in obj[a][b]){ //then third object (ocd-division/country:us)
if(c == 'name'){ //c is the key of the object which is name
console.log(obj[a][b][c]); //print in console the value of name which is United States.
obj[a][b][c] = "Canada"; //replace the value of name.
var objName = obj[a][b][c]; //or pass it on variable.
}
}
}
}
console.log(obj); //name: Canada
console.log(objName); //name: United States
You can also use this reference:
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements/for
http://stackoverflow.com/questions/8312459/iterate-through-object-properties

How does for(var x in object) work if there is initially no var x in the object, initially?

I have an object, and I'm trying to see what's inside of it. So, I used print(object), which should possibly contain Spot: True, indicating that the cat Spot is alive. It returned [object object]. So, I tried, show(object), and I got Spot: True. I think that's right, but I'm not sure what the indexes are like. For example, I'm not sure if the keys are associative or numeric, or even if associative arrays are allowed in JavaScipt.
The reason I wonder why is because for (var cats in object){show(cats);} returns Spot. I can't find a way to locate the string 'cat' as being part of the array.
The cats in your example is a new variable that holds each object of iteration.
And yes, "associative arrays" are allowed, but they're really just objects:
var foo = {
bar: "baz"
}
alert(foo.bar);
alert(foo["bar"]);
Re: the for/in statement: it's more or less the same as the following, here using an array:
var cats;
var arr = [42, 69];
for (var i = 0; i < arr.length; i++) {
cats = arr[i];
alert(cats);
}
Or you can use for/in and it becomes:
for (cats in arr) {
alert(arr[cats]);
}
It's slightly different for arrays, but there's no "cats" in the array, either.
Fiddle
Javascript has arrays and objects. Arrays have numeric continuous indexes [0..length) and ordered while objects can have random indexes (strings, numbers) and are not necessarily ordered (depends on the implementation).
Using for(var key in obj) {} should only be used for objects and iterates over the properties the object has. You can use obj[var] to access the value of each property.
Note that it's useful to add an if(!obj.hasOwnProperty(key)) continue; check to the loop to ensure you do not hit properties introduced in the object's prototype.
If object is your object, I'm guessing it's not actually an array. The for (var x in object) could also be enumerating the elements (properties, functions, etc.) of your object.
Where does your object come from? What are show() and print()?
If I was trying to print out the properties of an object I might have something like this:
var myObject = {
property1: 'Test',
property2: 'Test2',
function1: function() {
// do something
}
};
for (var prop in myObject) {
if (myObject.hasOwnProperty(prop)) {
console.log(prop + ' = ' + myObject[prop]);
}
}
This should output the following:
property1 = Test
property2 = Test2
function1 = function() { // do something }
Here's a jsFiddle to show the example.
With that said, JavaScript doesn't really have associative arrays. What you can have is an object with property:value pairs, which is what I think you have.

Parse 2 dimensional JSON array in Javascript

I have a two dimensional JSON array where each element contains several attributes. The example below is intentionally simplified:
var map_data = { "1":
{"1":{"name":"aa"},"2":{"name":"bb"}},
"2":
{"1":{"name":"cc"},"2":{"name":"dd"}}
};
I try to parse the data but .length doesn't work:
for(x=1; x<=map_data.length; x++) {
for(y=1; y<=map_data[x].length; y++) {
// CODE
}
}
Many, many thanks!
That's not an array, they are simple objects, that's why you cannot use the length property.
You need to use the for...in statement:
for(var x in map_data) {
if (map_data.hasOwnProperty(x))
for(var y in map_data[x]) {
if (map_data[x].hasOwnProperty(y)) {
// CODE
}
}
}
The hasOwnProperty checks are because this statement iterates over all properties, inherited or not, and if something (like some JavaScript frameworks) augmented the Array.prototype or Object.prototype objects, those augmented properties will be also iterated.
You should know that this statement doesn't ensure anyhow the order of iteration.
I would recommend you to use a "real" array:
[
[{"name":"aa"},{"name":"bb"}],
[{"name":"cc"},{"name":"dd"}]
]
In this way you will be able to use the length property to iterate over the indexes.
hasOwnProperty is used to determine whether an object has the specified property as a direct property of that object with no respect to it's prototype chain.
for(var i in map_data){
if(map_data.hasOwnProperty(i)){
for(var j in map_data[i]){
if(map_data[i].hasOwnProperty(j)){
/*do whatever you want with map_data[i][j]*/
}
}
}
}
Since map_data is an object instead of an array you need to use for/in loop:
for (var x in map_data) {
// check for hasOwnProperty omitted for simplicity.
for (var y in map_data[x]) {
// CODE.
}
}
But it's better to send that JSON as an array [a,b,c] instead of an object {"0":a,"1":b,"2":c}.
Use the for .. in construct:
for (var m in map_data) {
// ...
}
Also, I must note that this isn't a "JSON array", but rather a nested object. JSON is just the string representation of nested JS objects and arrays.
if it helps someone, its a example of c# and javascript:
c#:
List<List<string>> list_array = new List<List<string>>();
JavaScriptSerializer jss = new JavaScriptSerializer();
string _myJSONstring = jss.Serialize(list_array);
/*in this case list_array is a list bidimensional, but can be a single array,
if you print _myJSONstring, this will show like this: "[["XX","AAAA"],["YY","BBBB"]]" */
javascript:
into a function that get the string from c#:
var a = JSON.parse(array);
for (var t = 0; t < array.length; t++) {
for (v = 0; v < array[t].length; v++) {
alert(array[t][v]);
}
}

Categories

Resources