How to store objects in a array using javascript - javascript

i am developing extesnions for safari browswer. i want to store current active tab objects in a array as key. how to store multiple tab objects in a array.
i wrote following code.
**First scenario:
var obj = {};
obj1=new Object();
obj2=new Object();
obj3=new Object();
obj['cTab_'+obj1] = "This is object1";
obj['cTab_'+obj2] = "This is object2";
obj['cTab_'+obj3] = "This is object3";**
prblem is i am getting 3rd object value. how to get all the object values.
**Second scenario:
var arr = new Array();
cTabObj1 = new Object();
arr[cTabObj1] = 'This is cTabObj1 Value';
cTabObj2 = new Object();
arr[cTabObj2] = 'This is cTabObj2 Value';
cTabObj3 = new Object();
arr[cTabObj3] = 'This is cTabObj3 Value';
alert("arr[cTabObj1] :" + arr[cTabObj1] + " arr[cTabObj2] :" + arr[cTabObj2] + " arr[cTabObj3] :" + arr[cTabObj3]);**
Here also i am getting "This is cTabObj3 Value" for all three object
Thanks in advance.

i want to store current active tab objects in a array as key
You can't do that. Keys are strings. They always are strings.
If you take a look at the array you will find any object gets converted to "[object Object]" so your basically inserting the same key 3 times.
Use console.log(arr) or console.dir(arr) together with firebug or chrome/opera/safari
What you want is a ES6 WeakMap.
Only Firefox6 implements WeakMap

The keys need to be strings.
Try implementing the toString method on your objects so that it returns a unique identifier for each object. Then 'cTab_' + obj will be a unique string.

You should rather store like this
cTabObj1 = new Object();
arr["cTabObj1"] = cTabObj1;

Your first scenario is the way to go except that you have assigned the same subscript key to each object that you are storing in obj. When you use anything other than a string for an object property key, the value has toString() called on it internally, so
obj['cTab_'+obj1] = "This is object1";
obj['cTab_'+obj2] = "This is object2";
obj['cTab_'+obj3] = "This is object3";
will all have the same key of cTab_[object Object].
What you need is to differentiate the keys. Since each object will return "[object Object]" when toString() is called on it, you can remove the object from the property key too as it is redundant e.g.
var obj = {};
obj['cTab1'] = "This is object1";
obj['cTab2'] = "This is object2";
obj['cTab3'] = "This is object3";
or more tersely
var obj = {
cTab1 : "This is object1",
cTab2 : "This is object2",
cTab3 : "This is object3"
};
The reason why the second way is not the way to go is that you are trying to use a JavaScript array like an associative array, which they are not; it may seem to work at first but then you will discover some very odd behaviour, such as arr.length does not count them as items in the array, etc. For more details, read the linked article. You want to use Object ({}) for this.

Related

how to turn a string into a variable

Im trying to use a command for a chat program and i want to edit a variable with a command like !editvar variablehere value
so if it variablehere = '123' i want to turn '123' into just 123 or something like 'hello' into hello, in simple words im trying to make a string from a chat message into a variable name
ive tried parsing and string.raw and none worked
if(message.startsWith('keyeditvar')) {
console.log(message)
var bananasplit = message.split(' ');
var bananasplitted = json.parse(bananasplit)
console.log(bananasplitted[0].keyeditvar)
var variable = bananasplit[1]
console.log(variable)
var value = bananasplit[2]
console.log(value)
var variable2 = String.raw(variable)
console.log(variable2)
var value2 = String.raw(value)
console.log(value2)
}
i expected it to work ig
im trying to turn a string into a variable name
In Javascript, you don't usually dynamically define new variables with custom names in the current scope. While you can do it at the global scope, you cannot easily do it in the function or block scope without using tools that are generally not recommended (like eval()).
Instead, you use an object and you create properties on that object. You can use either a regular object and regular properties or you can use a Map object with some additional features.
For a regular object, you can do thing like this:
// define base object
let base = {};
// define two variables that contain variable name and value
let someName = "greeting";
let someValue = "hello";
// store those as a property on our base object
base[someName] = someValue;
console.log(base); // {greeting: "hello"}
Then, you can change the value:
someValue = "goodbye";
base[someName] = someValue;
console.log(base); // {greeting: "goodbye"}
Or, you can add another one:
let someOtherName = "salutation";
let someOtherValue = "Dear Mr. Green";
base[someOtherName] = someOtherValue;
console.log(base); // {greeting: "goodbye", salutation: "Dear Mr. Green"}
console.log(base.greeting) // "goodbye"
console.log(base[someName]); // "goodbye"
console.log(base.salutation) // "Dear Mr. Green"
console.log(Object.keys(base)) // ["greeting", "salutation"]
You can think of the Javascript object as a set of key/value pairs. The "key" is the property name and the value is the value. You can get an array of the keys with:
Object.keys(obj)
You set a key/value pair with:
obj[key] = value;
You get the value for a key with:
console.log(obj[key]);
You remove a key/value pair with:
delete obj[key]
With a plain Javascript object like this, the keys must all be strings (or easily converted to a string).
If you have non-string keys, you can use a Map object as it will take any object or primitive value as a key, but it uses get() and set() methods to set and get key/values rather than the assignment scheme of a plain object.
Please, next time put a clean code...
To convert a string to a number. You can use the function : Number(object)
So for example :
Number('123')
will return 123.
If the object value is not a correct number, it will return NaN.
So for example :
Number('hello')
will return NaN.

JavaScript drops Array Brackets in Object Key value pair

Hey guys I noticed something strange today with trying to set a key value pair in JavaScript. I know that The Key of an object is always 'stringified' so that the key value pair is always string: value, however something strange happened today when I tried this with an array. Example below:
var ob = {};
var a = [2,4];
ob[a] = 10;
console.log("this is ob ", ob);
Here I have tried adding the key [2,4] to map to 10. However, the console log returns the string 2,4 mapping to 10 instead of the string [2,4] mapping to 10. Does anyone know why this happens?
Using an object or an array as the property name, doesn't invoke JSON#stringify, but the object's toString method, which in arrays returns the array elements joined by a comma.
In the example I override the Array#toString method, and you can see that the resulting property name reflects that:
var ob = {};
var a = [2,4];
a.toString = function() { return 'cats' }; // override toString
ob[a] = 10;
console.log("this is ob ", ob);

Change key in js associative array

If I have:
var myArray = new Array();
myArray['hello'] = value;
How can I change the key 'hello' to something else?
Something like this would work.
var from = 'hello',
to = 'world',
i, value = myArray[from];
for( i in myArray )
if( i == from ) myArray.splice( i, 1 );
myArray[to] = value;
But is there a native function or a better way to do it?
edit:
Due to the lack of associative arrays in js, what I want to do modify the property name of an object as efficiently as possible.
In JavaScript there is no such thing as associative Array. Objects can be used instead:
var myHash = new Object();
or
var myHash = {};
replace can be done like this:
myHash["from"] = "value";
myHash["to"] = myHash["from"];
delete myHash["from"];
but the preferred way to write it:
myHash.from = "value";
myHash.to = myHash.from;
delete myHash.from;
You can't really "change" the property name, but you can always assign a property value to a new name, and then delete the original one.
myArray['world'] = myArray.hello;
delete myArray.hello;
Also, you're working with an Array instance but using it as a simple object; everything you're doing would work just as well with:
var myArray = {};
The "splice()" you're attempting in the code posted won't work, because it's only for the actual integer-indexed array properties, and not the named properties.
That "delete" doesn't really delete a property really doesn't matter. The "undefined" value is what you get when you check an object for a property and there's no such property.

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');

How to access the properties of a JavaScript object?

while review a javascript coding, i saw that
var detailInf = {
"hTitle":"Results",
"hMark":"98"
};
What's the concept behind this js coding. While give alert for the variable its shows as "[object Object]". So this is an object, then how can we access the variable and reveal the data from this object.
Try doing this:
alert(detailInf['hTitle']);
alert(detailInf.hTitle);
Both will alert "Results" - this is a Javascript object that can be used as a dictionary of sorts.
Required reading: Objects as associative arrays
As a footnote, you should really get Firebug when messing around with Javascript. You could then just console.log(detailInf); and you would get a nicely mapped out display of the object in the console.
That form of a JavaScript object is called an object literal, just like there are array literals. For example, the following two array declarations are identical:
var a = [1, 2, 3]; // array literal
var b = new Array(1, 2, 3); // using the Array constructor
Just as above, an object may be declared in multiple ways. One of them is object literal in which you declare the properties along with the object:
var o = {property: "value"}; // object literal
Is equivalent to:
var o = new Object; // using the Object constructor
o.property = "value";
Objects may also be created from constructor functions. Like so:
var Foo = function() {
this.property = "value";
};
var o = new Foo;
Adding methods
As I said in a comment a few moments ago, this form of declaring a JavaScript object is not a JSON format. JSON is a data format and does not allow functions as values. That means the following is a valid JavaScript object literal, but not a valid JSON format:
var user = {
age : 16,
// this is a method
isAdult : function() {
// the object is referenced by the special variable: this
return this.age >= 18;
}
};
Also, the name of the properties need not be enclosed inside quotes. This is however required in JSON. In JavaScript we enclose them in brackets where the property name is a reserved word, like class, while and others. So the following are also equivalent:
var o = {
property : "value",
};
var o = {
"property" : "value",
};
Further more, the keys may also be numbers:
var a = {
0 : "foo",
1 : "bar",
2 : "abz"
};
alert(a[1]); // bar
Array-like objects
Now, if the above object would have also a length property, it will be an array like object:
var arrayLike = {
0 : "foo",
1 : "bar",
2 : "baz",
length : 3
};
Array-like means it can be easily iterated with normal iteration constructs (for, while). However, you cannot apply array methods on it. Like array.slice(). But this is another topic.
Square Bracket Notation
As Paolo Bergantino already said, you may access an object's properties using both the dot notation, as well as the square bracket notation. For example:
var o = {
property : "value"
};
o.property;
o["property"];
When would you want to use one over the other? People use square bracket notation when the property names is dynamically determined, like so:
var getProperty = function(object, property) {
return object[property];
};
Or when the property name is a JavaScript reserved word, for example while.
object["while"];
object.while; // error
That's an object in JSON format. That's a javascript object literal. Basically, the bits to the left of the :'s are the property names, and the bits to the right are the property values. So, what you have there is a variable called detailInf, that has two properties, hTitle and hMark. hTitle's value is Results, hMark's value is 98.
var detailInf = { "hTitle":"Results", "hMark":"98"};
alert(detailInf.hTitle); //should alert "Results"
alert(detailInf.hMark); //should alert "98
Edit Paolo's answer is better :-)
As Dan F says, that is an object in JSON format. To loop through all the properties of an object you can do:
for (var i in foo) {
alert('foo[' + i + ']: ' + foo[i]);
}

Categories

Resources