在ES6中以这种方式过滤对象的最佳方法是什么?
开始数据:
const acceptedValues = ["value1","value3"] const myObject = { prop1:"value1",prop2:"value2",prop3:"value3" }
预期产量:
filteredObject = { prop1:"value1",prop3:"value3" }
解决方法
您可以使用reduce()创建新对象,并使用includes()来检查对象的值是否存在于数组中.
const acceptedValues = ["value1","value3"] const myObject = { prop1: "value1",prop2: "value2",prop3: "value3" } var filteredObject = Object.keys(myObject).reduce(function(r,e) { if (acceptedValues.includes(myObject[e])) r[e] = myObject[e] return r; },{}) console.log(filteredObject)