是否可以使用变量来解构对象?
Is it possible to use a variable to destructure an object?
我最近用这段代码回答了一个问题:
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'))
我试图像这样解构过滤器中的对象:
const findObject = (obj, prop, value) => obj.filter(({[prop]}) => prop === value)
但最终出现了这个错误:
Uncaught SyntaxError: Unexpected token }
是否可以使用变量(或在本例中为参数)名称解构对象?
你可以computed property names and a new variable for the value with a object property assignment pattern [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'));
我最近用这段代码回答了一个问题:
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'))
我试图像这样解构过滤器中的对象:
const findObject = (obj, prop, value) => obj.filter(({[prop]}) => prop === value)
但最终出现了这个错误:
Uncaught SyntaxError: Unexpected token }
是否可以使用变量(或在本例中为参数)名称解构对象?
你可以computed property names and a new variable for the value with a object property assignment pattern [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'));