[英]Can get parent object from child object in javascript?
正如標題所說,我有兩個 class 如下所示:
class A {
constructor() {
this.a = 1
this.b = 2
}
}
Class B extends A {
constructor() {
super()
this.c = 3
}
}
現在,我實例化 class B
const b1 = new B()
我可以使用某種方法從 b1 獲取 { a:1, b:2 }。 因為我需要通過API發布一些數據。 But my model is something like class B. but the interface of the API is like class A. So I just want to get the parent object from the child object. 提前致謝。
我可以使用某種方法從
b1
獲取{ a:1, b:2 }
嗎?
我將此解釋為意味着您想要一個 object 僅具有b1
中a
和b
屬性。 如果這是您的意思,那么您可以簡單地從b1
中選擇這些屬性並發布新的 object:
function pick (obj, keys) { const result = {}; for (const key of keys) result[key] = obj[key]; return result; } class A { constructor () { this.a = 1; this.b = 2; } } class B extends A { constructor () { super(); this.c = 3; } } const b1 = new B(); // Post this: const data = pick(b1, ['a', 'b']); console.log(data); // { a: 1, b: 2 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.