javascript, saving reference to nested object literal - javascript

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"}}}"

Related

how to recognize when to use : or = in JavaScript?

How can I recognize when to use : or = in my code? I came from Java which does not have many : in it, so it's a new thing for me.
= is used to assign a value to a variable:
myVariable = 'someValue';
: is used when defining a property of an object:
myVariable = {
key: 'value in an object'
};
When we want to define property of an object then we always use :
Syntax
var object = {
property1 : value1,
property2 : value2,
property2 : value3
}
We always separate properties with comma in a single object
= Equal to always use as a assignment operator which assigns values to variables or constants
Syntax
var variable=value
value can be any type You can see this document for that
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
Usually you use the : in objects for example:
object { car: 'BMW' }
And the = you use to define or update variables, example:
const car = 'BMW'; car = 'Mercedes-Benz'
: vs =
: is used in object, That is while assigning value's to key ex:-
const newObject = { key:value }
but when you assign some value to variable = sign is used

How to access properties of object by dot operator in Javascript

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.

How to access a parametric object property in JavaScript?

Object #1:
var chosenProperties = { 'size' : 'large' }
chosenProperties are properties that user wants to access from the below object. This object is created based on a form values.
Object #2:
var allProperties = { 'sizes' : { 'large' : 'x', 'small' : 'y' } }
Normally I would write allProperties.sizes.large to have x displayed but what if I need to access x if I only have chosenProperties? I'm sure that there is some method to do that but nothing comes to my mind.
Everytime the name of the property is contained in a different variable, you can use square brackets notation to access that property.
allProperties.sizes[chosenProperties.size]
UPDATE
Since ES2015 it's possible to use square brackets also inside an object literal.
var field = "foo";
const obj = {
[field]: "bar"
};
obj.foo; // bar
allProperties.sizes[chosenProperties.size]
if (chosenProperties.size) {
allProperties.sizes[chosenProperties.size]
}
not 100% sure what you are trying to do here but you know you can:
allProperties.sizes[chosenProperies.size]
Should return X

Class members in Backbone/Parse using each other

var User = Parse.User.extend({
// instance members
}, {
// types
TYPE_TRAINER : 1,
TYPE_ATHLETE : 2,
types: {
TYPE_TRAINER : 'Trainer',
TYPE_ATHLETE : 'Athlete'
}
});
I want to have TYPE_TRAINER and TYPE_ATHLETE maintain the values of 1 and 2 as defined prior to the types object so that I can use the types object in a template.
If you don't know about Parse, Parse.User is an extension of Backbone.Model.
Thanks!
What you're asking is not directly possible in JavaScript object literals. Object literals are always a literal value on the left hand / key side.
The closest you could get is to use the TYPE_TRAINER and TYPE_ATHLETE keys as variables to assign values via the square bracket syntax for accessing object key/value pairs:
var a = 1;
var b = 2;
var obj = {};
obj[a] = "a";
obj[b] = "b";
This will result in the obj object looking like this:
{
1: "a",
2: "b"
}
So you could do something like this, to get what you want in your code:
var userMethods = {
// types
TYPE_TRAINER : 1,
TYPE_ATHLETE : 2
};
userMethods[userMethods.TYPE_TRAINER] = 'Trainer';
userMethods[userMethods.TYPE_ATHLETE] = 'Athlete';
var User = Parse.User.extend({
// instance members
}, userMethods);
It's more code than you probably want, but it's the only way to achieve what you want because of the object literal syntax.
The Parse.Object Javascript documentation says:
You should call either:
var MyClass = Parse.Object.extend("MyClass", {
// Instance properties
}, {
// Class properties
});
or, for Backbone compatibility:
var MyClass = Parse.Object.extend({
className: "MyClass",
// Other instance properties
}, {
// Class properties
});
If you are wanting to extend the Parse.User "class" (it's an object, not a class), you need to include the className as described above because Parse.User is itself an extension of Parse.Object.

How to set a Javascript object values dynamically?

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];
});

Categories