Reputation: 6446
I recently answered a question with this code as an answer:
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'))
I tried to destructure the object in the filter like this:
const findObject = (obj, prop, value) => obj.filter(({[prop]}) => prop === value)
But ended up with this error:
Uncaught SyntaxError: Unexpected token }
Is it possible to destructure an object with a variable (or in this case parameter) name?
Upvotes: 4
Views: 68
Reputation: 386550
You could take a 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'));
Upvotes: 6