It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});
Related
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }
I have an object and I want to use object property value as key (simplified):
var App = function() {
this.settings = {
'tetris': {
title: 'Tetris'
},
'galaxian': {
title: 'Galaxian'
}
};
this.gameName = 'tetris';
this.request = {
this.settings[this.gameName].title: 'THIS KEY IS INVALID' // :(
}
};
I know I could assign it as:
this.request[ this.settings[this.gameName].title ] = 'Valid...';
But I wonder if I can define the property name using the object property value?
I am afraid, what you mean is not possible. You can not use a variable as a key in an object literal like this:
var key = "somekey";
var obj = {key: "value"}
The above code will result in an object that has the key key.
You can only use a variable to define an object element like this:
var key = "somekey";
var obj = {};
obj[key] = "value"
Then the object get's an element with the key somekey
EDIT: As stated in the comments, in ECMAScript 6 the support for computed properties in object literals got introduced. However the browser support for the computed properties in object literals is very slim (you can look it up here under syntax -> object literals). For example IE 11 has no support for it, neither has Chrome 43.
Computed property names will be introduced in ECMAScript edition 6, they're in the current draft, so you can do:
this.request = {
[this.settings[this.gameName].title]
}
They're reasonably well supported now, see MDN for more detail.
You can't define literal objects with computed property names; you have to assign them.
In other words, you can either define a literal object using {...} notation if the property name is well-known, or assign values into keys in a map using x[prop] = v notation if the property name is computed.
Think of your JS objects as being either objects or maps, but not both. If the JS object has well-known property names then it's acting as an object:
var obj = {
wellKnownPropertyName = 'value';
};
var value = obj.wellKnownPropertyName;
But if the property name is computed then it's not really a property of an object but more like a key in a map, and should be assigned (and read) as such:
var map = {};
var key = getUnknownKeyFromSomewhere();
map[key] = 'value';
var value = map[key];
Lets say I have the following object:
name = {
name_one : {
name_one_A : {
name_one_A_a : 'John',
name_one_A_b : 'Kate'
}
}
};
I could create a reference to 'John' by doing:
current_name = name.name_one.name_one_A.name_one_A_a;
Lets say I'm referencing "name.name_one.name_one_A" several times, is there a way to create a referencing to this nesting? This doesn't work, but something like:
A = name.name_one.name_one_A;
name = A.name_one_A_b;
'name' would then equal 'Kate'. I know this doesn't work like that, but I'm just wondering if there is a way to accomplish this?
Thanks for any help!
It's a bit hard to tell exactly what you're asking which has caused some confusion among the answers.
If you're referencing name.name_one.name_one_A multiple times, you can save that once and then use it:
var x = name.name_one.name_one_A;
x.name_one_A_a = 'Bill';
x.name_one_A_b = 'Sue';
This works ONLY because the value of name.name_one.name_one_A is an object (Object, Array or Function). So, when you save it to another variable, you aren't actually saving a reference to name.name_one.name_one_A, but rather getting the value of that property which is itself an object. And, when you then modify that object, since name.name_one.name_one_A also points to that same object, you will see the value change there too.
Javascript does not have the ability to create a reference to a particular property on an object such that you could use only that reference to then change the value of that property.
Using C/C++ terminology, you can't create a pointer to a property on an object in Javascript such that you could change the value in that property using only that pointer.
You would instead have to pass the host object and the property name and you could then change the value of the property on that host object.
Or, if the value of the property was itself an object (Object, Array or Function), then you can get the value of the property and then change the object that it points to.
So, in your data structure:
var name = {
name_one : {
name_one_A : {
name_one_A_a : 'John',
name_one_A_b : 'Kate'
}
}
};
There's no way to get a direct reference to:
name.name_one.name_one_A.name_one_A_a
that would let you modify just the contents of that property at some later time. Instead, you'd have do something like this where you get a reference to the containing object and use that:
var obj = name.name_one.name_one_A;
var prop = "name_one_A_a";
// and then some time later:
obj[prop] = 'Bob';
// or
obj.name_one_A_a = 'Bob';
Firefox Scratchpad had an issue with a variable named "name", but this works:
var foo = {
'name_one' : {
'name_one_A' : {
'name_one_A_a' : 'John',
'name_one_A_b' : 'Kate'
}
}
};
var A = foo.name_one.name_one_A;
console.log(A.name_one_A_b);
//yields
Kate
Update:
You can get a reference that is able to change a property value:
var foo = {
'name_one' : {
'name_one_A' : {
'name_one_A_a' : 'John',
'name_one_A_b' : 'Kate'
}
}
};
var A = foo.name_one.name_one_A;
console.log(A.name_one_A_b);
A.name_one_A_b = "bob";
console.log(A.name_one_A_b);
console.log(JSON.stringify(foo));
Yields:
"Kate"
"bob"
"{"name_one":{"name_one_A":{"name_one_A_a":"John","name_one_A_b":"bob"}}}"
var changeJsonKeyName, newObj, obj;
changeJsonKeyName = function(json, oldName, newName) {
json[newName] = json[oldName];
delete json[oldName];
// json.newName = json.oldName;
// delete json.oldName;
// if i use point in this ,i can not get my result that i want
return json;
};
obj = {
'aaa': '1111',
'bb': {
'cc': 333
}
};
newObj = {};
newObj = changeJsonKeyName(obj, 'aaa', 'nnn');
console.log(newObj);
If I use point here ,I can not get my result that's what I want ,what is the wrong,please help me,thank you very much.
I'm not sure if I understood you correctly, but :
json[newName]
access property named with the value of newName variable
json.newName
access a property named 'newName', which does not exist
First, as a comment points out, this is a Javascript question, not a JSON question.
But you seem to be asking why this works:
json[newName] = json[oldName];
delete json[oldName];
but this doesn't:
json.newName. = json.oldName.;
delete json.oldName;
does not.
And the answer is the second form is actually equivalent to
json["newName"] = json["oldName"];
delete json["oldName"];
In other words, you are dealing with attributes whose names are the constants "oldName" and "newName" rather than attributes whose names are passed as parameters to that method.
I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.
var name = "foo";
var array = [];
array["reference"] = name;
name = "bar";
// Still returns "foo" when I'd like it to return "bar."
array["reference"];
Is there a way to make the array refer to the variable?
Put an object into the array instead:
var name = {};
name.title = "foo";
var array = [];
array["reference"] = name;
name.title = "bar";
// now returns "bar"
array["reference"].title;
You can't.
JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.
If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".
Btw, [] is an array literal. {} is an object literal.
That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.
And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).
Try pushing an object to the array instead and altering values within it.
var ar = [];
var obj = {value: 10};
ar[ar.length] = obj;
obj.value = 12;
alert(ar[0].value);
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called myTarget, then use:
myRef = function (newVal) {
if (newVal != undefined) myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(<the value you want to set>);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray[0]() to read and myArray[0](<new value>) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called 'myTarget', then use:
myRef = function (newVal) {
if (newVal != undefined)
myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(value_to_set);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray0 to read and myArray[0](value_to_set) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.