Can get parent object from child object in javascript?

Viewed 43

As the title said, I have two class like below:

class A {
    constructor() {
       this.a = 1
       this.b = 2
    }
}
Class B extends A {
    constructor() {
       super()
       this.c = 3
    }
}

Now, I instance class B

const b1 = new B()

Can I use some method to get the { a:1, b:2 } from b1. Because I need to post some data through 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. Thanks in advance.

1 Answers

Can I use some method to get the { a:1, b:2 } from b1?

I interpret this to mean that you want an object with only properties a and b from b1. If that's your meaning, then you can simply pick those properties from b1 and post the new 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 }

Related