This question already has answers here:
Javascript: how to dynamically create nested objects using object names given by an array
(25 answers)
Closed 6 years ago.
I need to send a JSON object to a server which requires that the properties
are nested. For example, the data object may be nested 2 levels deep. However, one cannot simply declare the object directly:
var foo = {};
foo.bar.bartwo = "data"; //Uncaught TypeError
I am currently attempting to bypass this by manually creating the nested object layer.
var foo = {};
foo.bar = {};
foo.bar.bartwo = "data"; //Successful
However, this can quickly get out of hand if the object requires multiple levels of nesting.
Is there a better method in Javascript or Jquery to handle this issue (which does not work by simply golfing the second code example)?
Clarification: The solution should be able to allow for direct access to nested properties, without necessitating that all of the intermediate properties also be created.
without defining nested object i.e foo.bar = {};
you can not use or assign value to it
javascript object must be defined first to use it
otherwise it will give you 'undefined' error i.e foo.bar is undefined
create a small method that does this
function nested(x, y){
nestedA="";
parts = x.split('.');
for(i=0; i<parts.length; i++) {
nestedA += parts[i];
eval(nestedA + ' = {}');
nestedA += '.';
}
eval(nestedA.slice(0,-1)+ '= "'+y+'"');
}
nested('foo.bar.bartwo', "data");
Related
I am having difficulty in understanding the following code, i have put a comment where i do not understand the concept, what exactly is going on
var ob = {};
var ob2 = ['name'];
for(var op of ob2)
{
ob[op]='at'; // here i dont understand what is happening, why here is an array type brackets
}
console.log(ob);
OUTPUT IS
name:'at'
That is just the syntax for accessing or assigning properties of an object dynamically in javascript.
You can think of it as though you are doing: ob.name = 'at'.
There are two ways to access object properties in JavaScript
var person = {
name: 'Jane'
}
person.name
// or
person['name']
// both return jane
in your case, that iterates through members of the array called ob2
first and only element of that array is a string name and it's given to that object as a prop, which becomes like following
ob['name'] = 'at';
// or
ob.name = 'at';
When to use brackets([]) over dot(.)
If you don't know the prop name at runtime you need to go with brackets, if you do know it you can choose either dot notation or brackets
Basically, it's accessing a property of the object ob. In this case, is accessing and creating new properties.
The loop is getting each index value, and for each assign/create a new property using that index value.
That approach is a dynamically way of creating property-names in an object.
ob['name'] = 'at';
ob.name = 'at'; // Just to illustrate
Read a little the docs here -> JavaScript object basics - Learn web development | MDN
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 6 years ago.
I have a namespace and class declared in the client. In fact, I have a whole bunch of classes declared in several namespaces. I just need to get an instance of one of them when I get a string from the server on page load that contains the "dotted" namespace.class names.
Currently I use eval to do that but this causes a memory leak, so I'm trying to find an alternative way of instantiating a declared object by knowing only its name. Things like var obj = "myNamespace.myObjectName"(); won't work, obviously.
If I have an object name as a string variable I can use the eval() function to create an instance of that object:
window["myNamespace"] = {};
myNamespace.myObjectName = function() { /* blah */ };
var name = "myNamespace.myObjectName";
var obj = eval("new " + name + "()");
But for several reasons I don't want/cannot to use the eval. How can I create an object by its name without using the eval?
It sounds like you don't control the content of the name variable, so you're stuck with the . being part of the string.
Therefore, you can .split() the string into its name parts, and use .reduce() to traverse from the base object.
window["myNamespace"] = {};
myNamespace.myObjectName = function() {
this.foo = "bar"
};
var name = "myNamespace.myObjectName";
var obj = newObjectFromStringPath(name);
document.querySelector("pre").textContent = JSON.stringify(obj, null, 4);
function newObjectFromStringPath(path, base) {
return new (name.split(".").reduce(function(obj, name) {
return obj != null ? obj[name] : null
}, base || window))
}
<pre></pre>
The newObjectFromStringPath is coded to specifically target a function and call it as a constructor. You can easily make this work to fetch any value by simply removing the new in that function.
This question already has answers here:
Get property of object in JavaScript
(3 answers)
Closed 6 years ago.
I am trying to access a property within an object and return it.
Note the name of the object can change, so accessing it using title_can_change.property will not work.
Take the following object:
{
"title_can_change":{
property: 1
}
}
How do I return the value of 'property'?
MORE INFO:
This object is being returned from a search which contains an array of results from several API's. This object is returned to detail the API the result has come from (the search goes through several API's).
So this would be more like:
apiData:{
"apiName":{
price: 500
}
}
"apiName" is not fixed and changes to say the name of the API. So it cannot be referenced by "apiName' in any of the code.
You could create a function to return the value of the property of whatever object you pass to it:
var getProperty = function(obj) {
return obj.property;
};
If you have an object and you want to access it's first key's value you can go with something like this (dirty example):
var myObj = {
"title_can_change"{
property: 1
}
}
myObj[Object.keys(myObj)[0]];
I home this helps.
So I think I know what you are wanting and here is a low-level solution that may prove valuable and show you some neat things about the language.
https://jsfiddle.net/s10pg3sh/1/
function CLASS(property) {
// Set the property on the class
this.property = property || null;
}
// Add a getter for that property to the prototype
CLASS.prototype.getProperty = function() {
return this['property'];
}
var obj = new CLASS(9);
alert(obj.getProperty());
What you are doing in the above is creating a "class" for your new variable. When you create your object with the new keyword as show you still get your normal JS object (everything is an object anyways), but you get the convenience of the getProperty method. This being on the prototype insures that any new CLASS variables you create will have that method. You can change the variable names and you will always have access to that property by having access to the instance (variable). This is a very common OO paradigm and is the strength of a prototypical language so while it may be over the top for your needs I figured I would add it as an answer here...
If this object is global, then you can use window['title_can_change']['property']. If it's just another property of another object (called another_one) you can access it with another_one['title_can_change']['property'].
Furthermore: You can have a variable (let's call it title_name) to ease the call:
....
var title_name = "title_can_change";
var myObj = window[title_name]['property'];
title_name = "title_has_changed";
var anotherObj = window[title_name]['property'];
.....
OR
....
var title_name = "title_can_change";
var myObj = another_one[title_name]['property'];
title_name = "title_has_changed";
var anotherObj = another_one[title_name]['property'];
.....
Kind of a guess here since the question is still somewhat unclear. I am assuming that you want to iterate over an objects properties whose names are unknown.
This might be a solution.
for (var property in object) {
if (object.hasOwnProperty(property)) {
// check objects properties for existence
// do whatever you want to do
}
}
Use for...in to iterate over the keys of the object and check if your inner object contains your property
var o = {
"title_can_change":{
property: 1
}
};
for (var k in o) {
if (o.hasOwnProperty(k) && o[k].property) {
return o[k].property;
}
}
how can i create object using multiple variables for multiple property name.
I am trying to create multiple versions of an object which has an init function. I have tried using the javascript 'new' function but in this case that does not work and the console notifies me this is because it is not a function. See the code for a clearer description of what I am trying to do.
for (a=1;a<=5;a++)
{
json.name={};
json.name[a]={};
for (b=1;b<11;b++)
{
json.name[a][b]={};
json.name[a][b]=$("input#c"+b+"r"+a).val();
}
//json.name.1.3 = the value from the input
The problem is the fact you keep writing over the variable in the loop.
Move json.name={}; outside the for loop.
var a, b, json;
json.name = {};
for (a=1; a<=5; a++) {
json.name[a] = {};
for (b=1; b<11; b++) {
json.name[a][b] = $("input#c"+b+"r"+a).val();
}
}
It also seems weird you are using objects and not arrays and that you are starting at one and not zero.
This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I tried my best to think of a name of this question, I'll change it if I can get some terminology to help
Best way I can describe it is this
obj1 = {
"a":{"var":1},
"b":{"var":2},
"c":{"var":3}
}
// What's the difference between
resulta = obj1['a']['var']
// and...
resultb = obj1.a.var
So, what's the difference between using [''] and . ?
I realize you can only use . to run functions, but is that the only difference?
Is one method faster than the other? (even a little?)
The first method with square brackets is handy if you're dynamically building your object's property keys:
var myDynamicKey = "a";
var result = obj[myDynamicKey]["var"];
var result = obj["someOtherKey_" + myDynamicKey]["var"];
The second one is definitely preferred if you know what the properties are in advance.
Note you can mix and match them:
var result = obj[myDynamicKey].var;
I'd be willing to bet that accessing properties using dot notation is faster, but I have no actual data to support that.
If you use the [''] then you can pass the name of the key in as a dynamic variable... which can change at run time. If you use the .key.key method, then you have to know at build time what the keys are.
Example:
var keys = ['name','phone','email'];
var object = {"name": ,"phone": , "email"};
function updateKeys(name,phone,email){
for(var i = 0; i < keys; i++){
object[keys[i]] = arguments[i]
}
}
vs
function updateKeys(name, phone, email){
object.name = name;
object.phone = phone;
object.email = email
}
The [''] way is much more flexible and allows for more code resuse. Most libraries will use this, or some homegrown replacement of the [''] way of doing things.
There are various websites with information about this.
http://www.quirksmode.org/js/associative.html
or
http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)
or
http://www.mongodb.org/display/DOCS/Dot+Notation+(Reaching+into+Objects)
The first I would call dot notation which can be used to access Methods and Properties of an object, and the 2nd is Associative Array.