admin管理员组

文章数量:1245189

Given the following object {a:1, b:2, c:3} I'm looking for es6 syntax to distruct a subset of the object to a new one i.e: {b:2 ,c:3}.

I've found this syntax enabling me to omit the properties I don't want: const {a,...newObj} = original.

How can I do it, with including the properties names.

Given the following object {a:1, b:2, c:3} I'm looking for es6 syntax to distruct a subset of the object to a new one i.e: {b:2 ,c:3}.

I've found this syntax enabling me to omit the properties I don't want: const {a,...newObj} = original.

How can I do it, with including the properties names.

Share Improve this question edited Jan 10, 2018 at 14:38 Shlomi Schwartz 8,91330 gold badges119 silver badges198 bronze badges asked Jan 10, 2018 at 10:55 Roni GadotRoni Gadot 4773 gold badges19 silver badges31 bronze badges 5
  • Object spread/rest is not a part of the language yet, it will probably be included in ES 2018 though. There's not a easy syntax to do it. – Axnyff Commented Jan 10, 2018 at 10:57
  • Cool, but I'm working with Babel – Roni Gadot Commented Jan 10, 2018 at 11:00
  • @RoniGadot your Const {a,...newObj} = original works fine. Do you want to achieve something else. Please explain – Rohit Agrawal Commented Jan 10, 2018 at 11:03
  • 2 It works, but I want to cherry pick the fields I want and not omit the ones I don't – Roni Gadot Commented Jan 10, 2018 at 11:10
  • @RoniGadot, added my answer according to your requirement. Please let me know in case of some problem. – Rohit Agrawal Commented Jan 10, 2018 at 11:23
Add a ment  | 

4 Answers 4

Reset to default 10

One of the following single liners will do the job -

Using Object.fromEntries:

// if keys are guaranteed to exist in `obj` use:
Object.fromEntries(['key1', 'key2'].map((k) => [k, obj[k]]));
    
// if keys might not exist in `obj` use:
Object.fromEntries( Object.entries(obj).filter(([k]) => ['key1', 'key2'].includes(k)) );

Using Object.assign:

// if keys are guaranteed to exist in `obj` use:
Object.assign({}, ...(['key1', 'key2'].map((k) => ({[k]: obj[k]}))));

// if keys might not exist in `obj` use:
Object.assign({}, ...(['key1', 'key2'].filter(k => obj.hasOwnProperty(k)).map((k) => ({[k]: obj[k]}))));

Using object destructuring:

( ({key1, key2}) => ({ key1, key2 }) )(obj);

The above allows getting a new object without creating intermediate variables or objects.

For example -

var obj = {a:1, b:2, c:3};
var newObj = Object.fromEntries(['a', 'b'].map((k) => [k, obj[k]]));
console.log(newObj);

You can cherry pick the properties you want like shown below. The name of the new variable should be same as the property name. Then you can create a new object containing those picked properties.

var obj = {a:1, b:2, c:3};
var {b, c} = obj;//pick property b and c
var newObj = {b, c}; //shortcut for {b:b, c:c} in ES-6
console.log(newObj);

I'm not sure what you really want. But as far as I understood this will help you.

For example

I have the initial object

{ a: 10, b: 20, c: 100 }

Properties I want to extract are a, b

And I want to create new object c with property b, c

Here is how it is done. Using destructive assignment. Here the out put will be 20 as in the initial object.

({ a, b } = { a: 10, b: 20, c: 100 });
let c = {a: a, b: b};
console.log(c.b);

MDN Document to destructive assignment. link

If you switch from vanilla Javascript to its superset Typescript, this will bee a bit easier. I've made couple of functions for this kind of purposes:

To filter selected fields, from an object. You can use following:

/**
 * Return a subset object of the source object containing only listed fields 
 * @param source Source object
 * @param fields List of source object's fields to be included in a returning object 
 */
export const subset = <T>(source: T, ...fields: (keyof T)[]): Partial<T> => {
  return fields.reduce((prev, field) => ({
    ...prev,
    [field]: source[field],
  }), {});
};

To make filtering by listing fields to be excluded use following:

/**
 * Return a subset object of the source object with listed fields excluded 
 * @param source Source object
 * @param fields List of source object's fields to be included in a returning object 
 */
export const exclude = <T>(source: T, ...fields: (keyof T)[]): Partial<T> => {
  const result: Partial<T> = { ...source, };
  fields.forEach(field => delete result[field]);
  return result;
};

本文标签: javascriptDestructing partial object to a new object in jsStack Overflow