1

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.

5
  • 4
    var foo = {bar: {bartwo: "data"}}; Commented Jun 22, 2016 at 13:10
  • create simple "namespace" function. or google one Commented Jun 22, 2016 at 13:10
  • @naththedeveloper While your solution is more concise, it doesn't actually solve the root problem. The nesting may require multiple levels to be generated dynamically, which would not work with your example. Commented Jun 22, 2016 at 13:11
  • What you're asking is impossible because to add a property to an object, the object must exist. The best you can do is make a function that lessens the burden of doing so, like this one. Commented Jun 22, 2016 at 13:18
  • var foo['bar'] = {'a': 'b'} You can do something like this Commented Jun 22, 2016 at 13:19

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

10 Comments

Test your code. There are several syntax issues with it.
What is .= doing? Is it concatenation?
adding to the string
Concatenation is JS would be +=, but then you're overwriting the value with {} anyway. Run your code please.
thanks i missed that
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.