是否可以使用变量来分解对象?

Kob*_*obe 4 javascript destructuring ecmascript-6

我最近用以下代码回答了一个问题:

var jobs= [
  {"startDate": "5/2017", "endDate": null, "isCurrent": true, "seniority": "Senior",},
  {"startDate": "5/2013", "endDate": "5/2019", "isCurrent": false, "seniority": "Junior"}
]

// Answer
const findObject = (obj, prop, value) => obj.filter(obj => obj[prop] === value)
console.log(findObject(jobs, 'seniority', 'Senior'))
Run Code Online (Sandbox Code Playgroud)

我试图像这样在过滤器中分解对象:

const findObject = (obj, prop, value) => obj.filter(({[prop]}) => prop === value)
Run Code Online (Sandbox Code Playgroud)

但最终出现此错误:

未捕获的SyntaxError:意外令牌}

是否可以使用变量(或在这种情况下为参数)名称来破坏对象?

Nin*_*olz 7

您可以使用对象属性分配模式[YDKJS:ES6&Beyond] 来计算属性名称和该值的新变量。

const findObject = (obj, prop, value) => obj.filter(({ [prop]: v }) => v === value)

var jobs = [{ startDate: "5/2017", endDate: null, isCurrent: true, seniority: "Senior" }, { startDate: "5/2013", endDate: "5/2019", isCurrent: false, seniority: "Junior" }];

console.log(findObject(jobs, 'seniority', 'Senior'));
Run Code Online (Sandbox Code Playgroud)