One-Liner to Take Some Properties from Object in Es 6

One-liner to take some properties from object in ES 6

Here's something slimmer, although it doesn't avoid repeating the list of fields. It uses "parameter destructuring" to avoid the need for the v parameter.

({id, title}) => ({id, title})

(See a runnable example in this other answer).

@EthanBrown's solution is more general. Here is a more idiomatic version of it which uses Object.assign, and computed properties (the [p] part):

function pick(o, ...props) {
return Object.assign({}, ...props.map(prop => ({[prop]: o[prop]})));
}

If we want to preserve the properties' attributes, such as configurable and getters and setters, while also omitting non-enumerable properties, then:

function pick(o, ...props) {
var has = p => o.propertyIsEnumerable(p),
get = p => Object.getOwnPropertyDescriptor(o, p);

return Object.defineProperties({},
Object.assign({}, ...props
.filter(prop => has(prop))
.map(prop => ({prop: get(props)})))
);
}

How to get a subset of a javascript object's properties

Using Object Destructuring and Property Shorthand

const object = { a: 5, b: 6, c: 7  };

const picked = (({ a, c }) => ({ a, c }))(object);

console.log(picked); // { a: 5, c: 7 }

What is the most efficient way to copy some properties from an object in JavaScript?

You can achieve it with a form of destructuring:

const user = { _id: 1234, firstName: 'John', lastName: 'Smith' };
const { _id, ...newUser } = user;
console.debug(newUser);

How to destructure and reassign in one line using JavaScript

If you know what properties the object does have, and there aren't that many, you can list them and use rest syntax to gather the others into an object:

const { unwantedProp, ...params) = adData;
// use params

Otherwise, there isn't any incredibly simple syntax for what you want, though you could

const params = Object.fromEntries(
Object.entries(adData).filter(([key]) =>
['id', 'status', 'frequency'].includes(key)
)
);

In JavaScript ES6, how do I take just a few properties from a hash?

Another way to do it is by destructuring:

let {a, b, d} = x;
let y = {a, b, d};

This automatically takes out the properties you want to use.
Then you can put them back together with an object literal, which in ES6 doesn't require you to do { a: a, b : b }. You can just write { a, b } instead, if the names are the same.

In this case, a, b and d are also copied.

how to destruct part of properties from an object

Actually you don't need object destructuring, just simple assignment:

obj2 = { name: obj1.name, age: obj1.age }

Now, obj2 holds wanted properties:

console.log(obj2);
// Prints {name: "Bob", age: 20}

If you want to merge old properties of obj2 with new ones, you could do:

obj2 = { ...obj2, name: obj1.name, age: obj1.age }


Related Topics



Leave a reply



Submit