有什么方法可以简化此两行表达式? (重组和重组)

时间:2018-10-08 08:14:32

标签: javascript

这是表达式:

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

基本上,我想从一个对象中提取多个属性,然后使用这些属性创建一个新对象。感觉好像可以用更简单的方式表达,但是我没有想法。

2 个答案:

答案 0 :(得分:0)

您始终可以使用lodash拾取方法(Lodash Pick Documentation),这将产生一个直线。

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>

答案 1 :(得分:0)

您可以编写一个高阶函数来提取具有特定属性的对象:

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))

您也可以用这种方式定义pick(),尽管内部函数将使用与提取的键数量成比例的堆栈存储器:

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))