简体   繁体   中英

adding an object into another object that is in another object

Say that there are three objects, a note, a noteState, and history:

var note = {
    text: "hello new world"
}

var history = {}
var noteState = {}

how would i be able to add note into noteState, and then add noteState into history?

could i potentially do something like:

$.extend(noteState, {"note1": note});
$.extend(history, {"noteState1": noteState});

and if I were to refer back to it to grab the text from note, how would i go about doing so?

history.noteState1.note1.text  // ?

or is there another method to go about this? thank you!

Why don't you simply

var note = {
    text: "hello new world"
}

var history = {}
var noteState = {}

noteState.note = note;
history.noteState= noteState;
alert(history.noteState.note.text);//alerts hello new world

Yes, you can do that and you don't have to use extend, simply set the properties. You don't even have to use distinct names, so following will do just fine :

noteState.note = note;
history.noteState = noteState;

Then, just as you wrote, you could use

 history.noteState.note.text

to retrieve the nested properties.

我想你也可以使用prototype属性来链接你的对象

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM