Change key in js associative array - javascript

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.

Related

Keeping array keys in JavaScript

Is it a feasible solution to keep make arrays with _ids from mongodb database in front-end part?
Let us suppose that I need to maintain the status of people with their ids .
Is it good to associate things like this:
let arr=[];
arr['5bbaea8847910db52c7c3682']='p';
arr['5b9f6a1fd85effbb8acbd1fe']='a';
console.log(arr['5b9f6a1fd85effbb8acbd1fe']);
or Is It better to keep things like this :
let arr=[];
arr.push({
_id:5bbaea8847910db52c7c3682,
status:'p'
});
I fear if such big ids may lead to memory problems or such things. I have been a C++ programmer previously so it does not appear to be a cool thing to do. Is it OK to do such things in JavaScript ?
As said above, u can use object of objects:
let data = {};
data[5bbaea8847910db52c7c3682] = {
status: 'p'
}
Or a map:
let data = new Map();
data.set(5bbaea8847910db52c7c3682, { status: 'p' });
Better to make arr as an object instead of array. Below is an example of creating new object as well as adding/editing it's property.
let obj = {} // or obj = new Object()
obj['5bbaea8847910db52c7c3682'] = 'p'
obj['5b9f6a1fd85effbb8acbd1fe'] = 'a'
console.log(obj)
To delete certain property, simply use delete keyword:
let obj = {}
obj['5bbaea8847910db52c7c3682'] = 'p'
delete obj['5bbaea8847910db52c7c3682']
console.log(obj)
if the property name is reserved keyword or it's contains a whitespace or special characters, then the way to set/get the property's value it's the same like set/get on array. Other than that, dot notation can be used.
let obj = {}
obj.someProperty = 'old value'
obj['someProperty'] = 'new value'
console.log(obj.someProperty) // 'new value'
console.log(obj['someProperty']) // 'new value'
In this situation, it is better to use an array of objects (as you suggested), or simply an ordinary object:
let ob = {};
ob['5bbaea8847910db52c7c3682'] = 'p';
ob['5b9f6a1fd85effbb8acbd1fe'] = 'a';
console.log(ob['5b9f6a1fd85effbb8acbd1fe']);

Add a child to a JavaScript object with a variable name

Let's say I have a blank JavaScript object:
myObject {}
And I also have a variable:
var myChildObject = this.name.split('.')[1];
For the sake of an example, let's say that myChildObject equals "FooBar". Now, I want to add a child object to myObject with the name of "FooBar", only we can't hard code "FooBar". We have to use the variable name myChildObject.
I tried this:
myObject.appendChild(myChildObject);
That doesn't work.
The goal is this:
{
"myObject":{
"FooBar":{
"thing1":25,
"thing2":6
},
.....
}
But I need to build the entire thing dynamically, without the names (other than the root) being known ahead of time.
An object is a "key value" type of thing, a little bit like a Map in Java. have you tried something like this:
let myObject = {};
let myChildObject = "fooBar";
myObject[myChildObject] = {};
This way you have a "fooBar" key for your Object... now you have to decide what you want the value to be for that key.
Objects can only have key value pair. You cannot use one without other. If you don't want to assign a value then simply give undefined. If you don't know the name of the property then you can simply use the array type notation for an object "[]". Refer to code below
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] = undefined;
console.log(myObject.hasOwnProperty(myChildObject)); // true
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] ={
"thing1":25,
"thing2":6
};
I'd say
for(var key in myChildObject) {
myObject[key] = myChildObject[key]
}
No idea what your question means but myObject["foobar"] might be what you are looking for

Javascript setter and getter with key for object

I have an object in a variable var o={};
I want to do something like what .push() method doing in array for my object.
JS code:
// Array:
var ar=[];
ar.push('omid');
ar.push('F');
var got=ar[1];
// above code is standard but not what I'm looking for !
/*-------------------------------------*/
// Object:
var obj={};
/* obj.push('key','value'); // I want do something like this
var got2=obj.getVal('key'); // And this
*/
Is this possible at all ?
var obj = {}
// use this if you are hardcoding the key names
obj.key = 'value'
obj.key // => 'value'
// use this if you have strings with the key names in them
obj['key2'] = 'value'
obj['key2'] // => 'value'
// also use the second method if you have keys with odd names
obj.! = 'value' // => SyntaxError
obj['!'] = 'value' // => OK
Since Object-Literals use a Key->Value model, there is no JS method to "push" a value.
You can either use Dot Notation:
var Obj = {};
Obj.foo = "bar";
console.log(Obj);
Or Bracket Notation:
var Obj = {},
foo = "foo";
Obj[foo] = "bar";
Obj["bar"] = "foo";
console.log(Obj);
Consider reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, as arming yourself with this knowledge will be invaluable in the future.
Here is some javascript magic that makes it work.
Take a look.
var obj = {};
Object.defineProperty(obj,'push',{
value:function(x,y){
this[x]=y;
}
});
obj.push('name','whattttt'); <<<this works!!!
obj;
//{name:'whattttt'}
obj.name or obj['name']..
//whattttt
The reason i defined .push function using Object.defineProperty because i didn't want it to show up as a property of object. So if you have 3 items in object this would have always been the 4th one. And mess up the loops always. However, using this method. You can make properties hidden but accessible.
Though i don't know why you would use this method when there is already a easy way to do it.
to assign a value do this
obj.variable = 'value';
if value key is number or weird do this...
obj[1] = 'yes';
to access number or weird name you also do that
obj[1];
and finally to assign random keys or key that has been generated in code, not hard coded, than use this form too.
var person= 'him';
obj[him]='hello';

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 implement such an associative array?

arr[key] = value;
where key is a jQuery object and value is an array.
Associative arrays don't really exist in JavaScript. However, you can achieve similar functionality using JavaScript objects:
// Create object
var myObject = {
key: value,
helloText: "Hello World!"
};
// Access object in some statement via:
myObject.helloText
// ...or:
myObject["helloText"]
To use an object as a key, you would have to do something like:
var a = {
helloText: "Hello World!"
};
var b = {};
b[a] = "Testing";
alert(b[a]); // Returns "Testing" (at least, in Safari 4.0.4)
Using an object as a key sounds a bit weird, though. Are you sure you need to do this?
Update:
You can't actually use an object as a key in JavaScript. The reason the above code appears to work is that, in the statement b[a] = "Testing";, JavaScript converts a to a string via a.toString(), which results in "[object Object]", and uses this string as the key. So our statement is actually b["[object Object]"] = "Testing"; and our alert statement is exactly the same as alert(b["[object Object]"]);.
Thanks to CMS for pointing this out in the comments!
Update 2:
Tim Down points out that his JavaScript library jshashtable allows you use an object as a key.
You can use jshashtable, which allows any JavaScript object as a key.
Just guessing here, but it seems you're trying to associate some (arbitrary) data with a jQuery object (possibly an element). In that case, why not use the data () method?
$('#el').data (value);
You can't use objects as keys, and assocative arrays are not what they seem in Javascript because all you're doing is setting a property on the array object, when you loop through by the .length it natively doesn't account for the manually defined properties you set.
I suggest storing the elements and arrays inside of object literals, all inside of an array. Eg:
var list = [
{
el:document.body,
arr:[1,2]
}
];
for ( var i = 0, l = list.length; i<l; ++i ) {
alert( list[i]['el'] )
alert( list[i]['arr'][0] )
}
// add elements to the array
list.push({
el:document.body.firstChild,
arr:[3,4]
})
As kprime mentioned in his answer though, it might be better to use .data() if you are using Javascript.
if ( !$(el).data('key') ) {
$(el).data('key', [2,3,4] );
}
I would suggest assigning a unique ID to each element you want to put in the associative container (object in JS) and use the ID as key:
var idCounter = 0;
var container = { };
function storeValue(element, value) {
if (!element.getAttribute('id')) {
element.setAttribute('id', makeID());
}
var id = element.getAttribute('id');
container[id] = value;
}
function makeID() {
return 'unique-id-' + idCounter++;
}
EDIT: This solution assumes that jQuery is not available. If it is, use data('key', value).
every javascript object is an associative array, this is a property build in the language, you do not need to anything special, just use it like that

Categories

Resources