我最近用以下代码回答了一个问题:
char * str = strdup("Hello World!");
free(str);
if(str) { // If str is not a null pointer'
puts(str); // str is pointing to memory that we have freed.
}
我试图像这样破坏过滤器中的对象:
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'))
但最终出现此错误:
未捕获的SyntaxError:意外令牌}
是否可以使用变量(或在这种情况下为参数)名称来破坏对象?
答案 0 :(得分:7)
您可以使用computed property names来获取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'));