如何在JavaScript中将所选属性从一个对象复制到另一个对象

时间:2017-10-22 16:10:59

标签: javascript

我想在纯javaScript中创建一个用于学习目的的库管理系统。我想将书的ID和名称复制到学生对象中。

var book = {
    id: "b1",
    name: "JavaScript",
    price: "$10",
    author: "Jack"
}

var student = {
    id: "S1",
    name: "Rob",
    bookList:[]
}

我想这样做:

var student ={
    id: "S1",
    name: "Rob",
    bookList:[{id:"S1", name:"JavaScript"}]
}

伙计们,如果还有其他方法可以实施图书馆管理,请告诉我们......

1 个答案:

答案 0 :(得分:0)

你可以推送到数组

student.bookList.push({ id: book.id, name: book.name });

<强>样本

var book = {
    id: "b1",
    name: "JavaScript",
    price: "$10",
    author: "Jack"
}

var student = {
    id: "S1",
    name: "Rob",
    bookList:[]
}

student.bookList.push({ id: book.id, name: book.name });

console.log(student);

如果您需要在学生中放置多本书,请继续推送 bookList 下的对象。

<强>样本

   var book = {
        id: "b1",
        name: "JavaScript",
        price: "$10",
        author: "Jack"
    }
   var book2 = {
        id: "b2",
        name: "AngularJs",
        price: "$15",
        author: "Tod"
    }
    var student = {
        id: "S1",
        name: "Rob",
        bookList:[]
    }
  
    student.bookList.push({ id: book.id, name: book.name });
    
    student.bookList.push({ id: book2.id, name: book2.name });
    

    console.log(student);