Object Extract Method Suggestion

# Murat Gözel (8 years ago)

Hey everyone,

The idea came up while i'm filtering spesific view of web page's text objects from whole context object. Objects are much more useful than any other type in many cases. I find myself working with more javascript objects project to project. Despite this, an object extract method can be useful for many cases. You can think of it as the opposite of assign method. It reduces the source object to a smaller object with only keys you spesified.

Looks like this:

Object.extract(SourceObject, ArrayOfKeys)

Example usage:

const contactPageExpressions = ['Follow Us', 'Phone', 'Email']

const wholeContext = {
  'Welcome': {
    translation: 'Welcome'
  },
  'Follow Us': {
    translation: 'Follow Us'
  },
  'Phone': {
    translation: 'Phone Number'
  },
  'Email': {
    translation: 'Email Address'
  },
  'News': {
    translation: 'News'
  }
}

const activeContext = Object.extract(wholeContext, contactPageExpressions)

// Now we have an object that only has keys we want:
{
  'Follow Us': {
    translation: 'Follow Us'
  },
  'Phone': {
    translation: 'Phone Number'
  },
  'Email': {
    translation: 'Email Address'
  }
}

Since it works by matching keys, second parameter of the method can even be a regular expression:

// Get properties that has numbers.
Object.extract(source, /[0-9]/g)

Would like to hear your opinions.

# Matthew Robb (8 years ago)

Personally I've been itching for object pattern-like pick syntax. I keep finding myself doing the following pattern:

const {a=1,c=2} = obj;
return {a,c};
# Bob Myers (8 years ago)

This has been discussed at length. You can search the archives for "picking" or "pick notation" or "destructuring into objects". There are several proposals. No one seemed too interested, although to me it's a mystery why, since it would be one of the more useful language features I can think of, with quite a low language design footprint. In one proposal rtm/js-pick-notation/blob/master/minimally-extended-dot-notation.md,

what you want (without the defaults, although the proposal supports that too) would be written

return obj.{a, c};

Bob