Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

javascript - Adding property to another property

why when adding a property to another property I get undefined error

var object={};
object["test"]= 404;
console.log(object);

{ test: 435 }          // Output

The above works fine, But when I try to add more property so as to have more phase of properties I receive undefined error.

var object={};
object["test"]["why"]= 404;
console.log(object);

TypeError: Cannot set property 'why' of undefined  // Output

Expected the below output

{ test: why: 435 }
question from:https://stackoverflow.com/questions/65918567/adding-property-to-another-property

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...