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
user5858
1,2417 gold badges42 silver badges86 bronze badges
-
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.Software Engineer– Software Engineer2016年03月03日 10:54:50 +00:00Commented Mar 3, 2016 at 10:54
2 Answers 2
You can do like this
obj = {
"train-11456": {
"2016-12-11": {
"chair car" : "waitlisted"
}
}
};
OR
obj = {"train-11456":{"2016-12-11":{"chair car":"waitlisted"}}};
Sign up to request clarification or add additional context in comments.
3 Comments
Siva
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.
user5858
also it discards earlier object data. Of little use.
Siva
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
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
years_of_no_light
9581 gold badge10 silver badges25 bronze badges
Comments
lang-js