If you want object.test
to be an object, you need to create that object (jus tlike you created the original you assigned to object
), it won't be created automatically for you. So:
var object = {};
object.test = {};
object.test.why = 404;
console.log(object);
You can create and populate the object in one step:
var object = {};
object.test = {why: 404};
console.log(object);
Indeed, you can do the whole thing in one step:
var object = {
test: {
why: 404
}
};
console.log(object);
Here are those examples using the bracketed notation with strings that you were using, but note that when the property names are known in advance (rather than determined dynamically at runtime), that's generally not best practice:
var object = {};
object["test"] = {};
object["test"]["why"] = 404;
console.log(object);
var object = {};
object["test"] = {why: 404}; // Or `{"why": 404}`, but that is *not* a dynamic name, see below
console.log(object);
If you wanted to use dynamic names with the object literal properties, you could do that with computed property name syntax, but again there's no good reason to here:
var object = {
["test"]: { // Computed namne, but no reason for it when you know the name at authoring time
["why"]: 404 // Again
}
};
console.log(object);
Side note: In modern JavaScript, there's (almost) never a good reason to use var
. Use let
or const
instead. If you have to support obsolete environments that don't support ES2015+, use a transpiler rather than trying to write obsolete code. :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…