1

I want to quickly assign like this:

obj = {};
obj["train-11456"]["2016-12-11" ]["chair car"] = 'waitlisted';

All those elements are objects.

We can do this in PHP and it creates them all automatically.

What is the simplest way to assign like this?

Longer way is:

obj["train-11456"] = {} //only if this key does not already exist
obj["train-11456"]["2016-12-11" ] = {}; //only if this key does not alreadu exist
obj["train-11456"]["2016-12-11" ]["chair car"] = 'waitlisted';
asked Mar 3, 2016 at 10:49
1
  • You can't do that directly in javascript as arrays (which is what the [] brackets represent) can only have numeric indexes. This is an OO language (ish) so you have to deal with objects. Commented Mar 3, 2016 at 10:54

2 Answers 2

3

You can do like this

obj = {
 "train-11456": {
 "2016-12-11": {
 "chair car" : "waitlisted"
 }
 }
};

OR

obj = {"train-11456":{"2016-12-11":{"chair car":"waitlisted"}}};
answered Mar 3, 2016 at 10:54
Sign up to request clarification or add additional context in comments.

3 Comments

obj["train-11456"]["2016年12月11日" ]["chair car"] The difference i feel is, the curly braces instead of square brackets and closed at the end instead of immediate. The number of curly brackets and square brackets are same if you see.
also it discards earlier object data. Of little use.
If you already defined obj["train-11456"]["2016年12月11日" ], then you are free to use obj["train-11456"]["2016年12月11日" ]["chair car"] = 'waitlisted'; without any issues
2

Well there is no straight way to do this. But you can write a utility function to do it for you. Its kind of shorthand

function objUtil (obj) {
 var _o = obj || {};
 return function () {
 var args = [].slice.call(arguments, 0),
 val = args.splice(args.length - 1, 1)[0],
 res = {},
 index, length, key, objPointer, lastObjPtr;
 objPointer = _o;
 for (index = 0, length = args.length; index < length; index ++) {
 key = args[index];
 lastObjPtr = objPointer;
 objPointer = objPointer[key] = {};
 }
 lastObjPtr[key] = val;
 return _o;
 }
}

And then call it like

var obj,
 populateObj = objUtil(obj={});
populateObj('train-11456', '2016-12-11', 'chair car', 'waitlisted');
console.log(obj);
answered Mar 3, 2016 at 11:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.