Object, Array and $.each() - javascript

I thought I solved my problem using the for (var key in arr) suggested here but this causes trouble in IE. Now I am back to square one.
var myVariable = [];
myVariable['option-1'] = 'something';
myVariable['option-2'] = 'something else';
$.each(myVariable, function(index, value) {
alert(index + ': ' + value);
});
It doesn't work. Nothing shows. Can someone edit it to make it work?

Just use an object instead of an array:
var myVariable = {};

Change var myVariable = []; to var myVariable = {};.
The syntax that you're using, myVariable['option-1'] = 'something'; is for objects, not arrays.

myVariable is an array. To add things to an array you use myVariable.push('something'). You are using square bracket syntax, which is how you would normally add properties to an object.
Since arrays are objects, you can still access option-1, but it is not a member of the array, it is a property of the object: myVariable['option-1']; // "something"
The solution is to set myVariable to an object. jQuery's each method will iterate over the properties of the object as expected.

No need for jQuery.
Just use a for..in loop (with an object {} not an array []):
for(var index in myVariable) {
var value = myVariable[index];
alert(index + ': ' + value);
}

There are no associative arrays in JavaScript, and non-numeric properties on arrays are bad practise!.
Instead, use an object literal:
var myVariable = {};
// ^^
myVariable['option-1'] = 'something';
…

Related

JS access an array with in an object

I have a variable holding a string of validated JSON. The JSON is a set of strings each with a value of an array. I'd like to access the string and each array value.
var json_string = {"div-1":["div-1A", "div-1B"], "div-2":["div-2A", "div-2B"]};
//Run some code to get the following result:
console.log("div-1" has "div-1A");
console.log("div-1" has "div-1B");
console.log("div-2" has "div-2A");
console.log("div-2" has "div-2B");
I have tried a bunch of different things but nothing seems to work right. Additionally, I get a weird functionality. If I do the following:
console.log(json_string["div-1"]);
I randomly get the following results for each page refresh :
div-1A //initial load
div-1C //refresh 1
div-1A //refresh 2
div-1B //etc
div-1A //etc
Any ideas how I can get what I am after?
You can first retrieve the values from keys and then use forEach to get their value
var json_string = {"div-1":["div-1A", "div-1B"],
"div-2":["div-2A", "div-2B"]
};
for(var key in json_string){
var _getValue = json_string[key]
if(_getValue.constructor===Array){ // Checking if it is an array
_getValue.forEach(function(item){
document.write('<pre>'+item+'</pre>')
})
}
JSFIDDLE
It'll be something like this if I understand correctly. You have to traverse through each property and take the array property value against that key.
for (key in json_string) {
var arr = json_string[key];
arr.forEach(function(item) {
console.log(key + ' has ' + item);
});
}
Use Object.keys() for getting all object keys and Array#forEach for iterating over array.
var json_string = {
"div-1": ["div-1A", "div-1B"],
"div-2": ["div-2A", "div-2B"]
};
// Get all object keys and iterate over them
Object.keys(json_string).forEach(function(key) {
// Get inner array using key and iterate
json_string[key].forEach(function(el) {
console.log(key + ' has ' + el)
});
});
For older browser check polyfill option for Object.keys method and forEach method.
It looks like your json_string is actually a JSON object (there's a difference). That said, keys within an object do not follow any sort/ordering. You will need to sort your keys before your output:
var obj = {
"div-1": ["div-1A", "div-1B"],
"div-2": ["div-2A", "div-2B"]
};
Object.keys( obj ).sort().forEach( key =>
obj[ key ].sort().forEach( val =>
console.log( [key,'has',val].join(' ') )
)
);
Of course you could also write your own function to output values for a specific key. Below adds a prototype function to Object, which is just an example (prototyping is generally not recommended):
Object.prototype.valuesFor = function(key){
this[key].sort().forEach( val =>
console.log( [key,'has',val].join(' ') )
)
return this[key];
};
var obj = {
"div-1": ["div-1A", "div-1B"],
"div-2": ["div-2A", "div-2B"]
};
obj.valuesFor('div-1')

How to get javascript object property using part of name

I have property yaCounter27352058 in window object.
I can easily get it using bracket notation
window["yaCounter27352058"]
The problem is that I don't know object id, so in general I want to get all objects like this
window["yaCounter*"]
You can query based of Object.keys:
var values = Object.keys(window).filter(function(el) {
return /^yaCounter.*?/i.test(el);
});
Then you can iterate:
values.forEach(function(key) {
console.log(key, window[key]);
});
Well, in fact you can't.
But you can do something else.
You can try to list all your properties with
var properties = Object.keys(window).
Then with a regexp you will select your properties starting with yaCounter :
var reg = new RegExp("^yaCounter.*");
var goodProp = [];
properties.forEach(function(prop) {
if (reg.exec(prop) != null)
goodProp.push(prop);
}
And them use these with :
goodProp.forEach(function(val) {
window[val];
}));

Parsing JSON using javascript only

I tried looking for a similar question, couldn't find anything detailed enough.
I have a an ajax call, which calls a php page and the response is:
echo json_encode($cUrl_c->temp_results);
Which outputs:
{"key":"value", "key2":"value"}
The output is being "parsed" using:
var json_response = JSON.parse(xmlhttp.responseText);
I was looking for a way to iterate through the response, and getting
the key and value using javascript only.
is the returned output considered valid json ?
How do I loop through it (no jquery just javascript) ?
To iterate through the items of an object, you normally use a for..in loop, which let you access the keys (property names) as well as the property values:
for (var key in object) {
var item = object[key];
}
And yes, {"key":"value", "key2":"value"} is valid JSON.
To answer your first question, yes it is considered valid JSON once you parse it with JSON.parse(), as you have. To answer your second question, have a look at for...in from the MDN.
You could use the first example in the doc to find out how to get the keys and values.
Example 1
var o = {a:1, b:2, c:3};
function show_props(obj, objName) {
var result = "";
for (var prop in obj) {
result += objName + "." + prop + " = " + obj[prop] + "\n";
}
return result;
}
alert(show_props(o, "o")); /* alerts: o.a = 1 o.b = 2 o.c = 3 */

How can I add a array as a property with the following syntax?

var Items = {
FormVariables: function()
{
if (this.array === 'undefined')
{
this.array = [];
}
return this.array;
}
};
This was my attempt at it and I get an error of it being undefined. Can I even have variables within Items scope like I am attempting. If so, what does the syntax look like?
I am only asking if this can be done using the var variableName = {} syntax.
EDIT:
Accessing it
var formVars = new Array();
formVars.push('[');
for (var item in gd["FormVariables"])
{
formVars.push('"' + item + '":"' + gd["FormVariables"][item] + '"');
}
formVars.push(']');
The real goal here is to take all these items and convert it to a JSON array of key/value pairs
Yes, you can use []. [] is a shortcut for new Array, just like {} is for new Object.
this.array = [];
By the way, there are no 'compiler errors' since JavaScript is not a compiled language but an interpreted one.
Also, your checking does not make much sense. You'd probably want:
if (typeof this.array === 'undefined')
since typeof returns a string. Checking for the string 'undefined' is not the same as checking for 'real' undefined. For the string, it must have been set explicitly to those characters, which is almost never the case.

variable as index in an associative array - Javascript

I'm trying to create an associative array, create an empty array, and then add a (indexName -> value) pair:
var arrayName = new Array;
arrayName["indexName"] = value;
// i know i can also do the last line like this:
arrayName.indexName = value;
When I assign the value to the indexName I want indexName to be dynamic and the value of a variable. So I tried this:
arrayName[eval("nume")] = value;
Where:
var var1 = "index";
var var2 = "Name";
var nume = '"' + var1 + var2 + '"';
but: alert(arrayName["indexName"]); doesn't return "value"... it says "undefined"
Is there something I’m missing? (I’m not familiar with eval() ); if the way I’m trying is a dead end, is there another way to make the index name of the associative array value dynamic?
At first I don't think you need a real array object to do what you need, you can use a plain object.
You can simply use the bracket notation to access a property, using the value of a variable:
var obj = {};
var nume = var1 + var2;
obj[nume] = value;
Array's are simply objects, the concept of an "associative array" can be achieved by using a simple object, objects are collections of properties that contain values.
True arrays are useful when you need to store numeric indexes, they automatically update their length property when you assign an index or you push a value to it.
You would use objects to do that:
var hash = {}
hash["foo"] = "foo";
hash.bar = "bar";
// This is the dynamic approach: Your key is a string:
baz = "baz"
hash[baz] = "hello";
To iterate, just use a for loop or $.each() in jQuery.
use arrayName[var1+var2]
Note that arrayName.var is the same as arrayName["var"] -- it's just syntactic sugar. The second form is mostly used when dealing with the kind of problems that you are facing - dynamic object keys, and keys that are not alphanumeric (think of arrayName[".eval()"]; this is a perfectly legal object key that has nothing to do with the javascript eval() function)
Are you looking for variableName = 'bla'+'foo'; arrayRef[variableName] = 'something'; ?
And even so, you should use an object literal instead. x = {}; x[variablename] = 'blah';
You want a plain object with the same bracket notaiton here, like this:
var arrayName = {};
arrayName["indexName"] = value;
Indeed, there was no need for an array object, a simple object did the job; further more an array introduced the need to use quotes inside the square brackets obj["var1 + var2"] to access the object property's value and not the value associated with an index (i think); the quotes transformed "var1 + var2" into a string. Using a simple object eliminated the need for quotes, so I can use obj[var1 + var2], wich worked :)
Thanks everyone !
I did something like like following;
let parentArray = [];
let childArray = [1, 2, 3];
childArray.name = 'my-array-1';
parentArray.push(childArray);
To access that by name in ES6;
parentArray.filter(x => x.name == 'my-array-1');

Categories

Resources