Create object containing only some attributes of another

Asked

Viewed 73 times

-2

Is there any possibility of creating an object with only a few attributes of another?

In Adonis, it is possible to filter which exact fields to pick from one request object and already create another in a very nice way.

Ex:

const user_data = request.only(['name', 'email'])

Which is the same thing as doing:

const user_data = { name: request.all().name, email: request.all().email }
  • using prototype think it is possible

  • You can use normal JS destruction as long as you know the exact structure of the object and where are the properties you are interested in. This request comes from where ? What are the properties you have ?

1 answer

3

You can add to the prototype something similar (not very advised) or create a function for it. Using a function for this could be like this:

function getSubSet(object, types) {
  return types.reduce((obj, type) => {
    return {
      ...obj,
      [type]: object[type]
    }
  }, {});
}

const request = {
  foo: 1234,
  bar: 5678,
  baz: 90
};

const user_data = getSubSet(request, ['foo', 'baz'])
console.log(user_data);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.