1

Here's the expression:

const { property1, property2 } = someObject;
return { property1, property2 };

Basically, I want to extract several properties from one object and then create a new object just with those properties. It feels as if it could be expressed in a simpler way, but I'm out of ideas.

kace91
  • 721
  • 1
  • 5
  • 20
  • 2
    Possible duplicate of [Is it possible to destructure onto an existing object? (Javascript ES6)](https://stackoverflow.com/questions/29620686/is-it-possible-to-destructure-onto-an-existing-object-javascript-es6) – smnbbrv Oct 08 '18 at 08:17
  • Possible duplicate of [One-liner to take some properties from object in ES 6](https://stackoverflow.com/questions/25553910/one-liner-to-take-some-properties-from-object-in-es-6) – str Oct 08 '18 at 08:19
  • how about merging the objects? then returning the value – Nelson Owalo Oct 08 '18 at 08:21

2 Answers2

0

You could always use the lodash pick method (Lodash Pick Documentation) this will give a one-liner.

const obj = { property1: "property1", property2: "property2", property3: "property3"};

function testPick(someObject) {
    return _.pick(someObject, ["property1", "property2"]);
}

console.log("testPick: ", testPick(obj));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Terry Lennox
  • 17,423
  • 2
  • 18
  • 28
0

You could write a higher order function to extract an object with specific properties:

const pick = (...p) => o => p.reduce((a, k) => Object.assign(a, { [k]: o[k] }), {})

// usage
const someObject = {
  property1: 'property1',
  property2: 'property2',
  property3: 'property3'
}
// function that extracts these two properties from an object
const pair = pick('property1', 'property2')

console.log(someObject)
console.log(pair(someObject))

You could also define pick() this way, though the inner function would use stack memory proportional to the amount of keys extracted:

const pick = (...p) => o => Object.assign({}, ...p.map(k => ({ [k]: o[k] })))

// usage
const someObject = {
  property1: 'property1',
  property2: 'property2',
  property3: 'property3'
}
// function that extracts these two properties from an object
const pair = pick('property1', 'property2')

console.log(someObject)
console.log(pair(someObject))
Patrick Roberts
  • 40,065
  • 5
  • 74
  • 116