filter过滤对象
1. 定义测试参数。
let obj = { a: 1, b: 2, c: 3 };
2. 定义js代码。
function filterObj(obj, arr) {
if (typeof (obj) !== "object" || !Array.isArray(arr)) {
throw new Error("参数格式不正确")
}
const result = {}
Object.keys(obj).filter((key) => arr.includes(key)).forEach((key) => {
result[key] = obj[key]
})
return result
}
3. 使用定义的js代码。
let newObj = filterObj(obj,["a", "b"]);
4. 测试结果。
newObj{ a: '1', b: '2' }