如何判断对象是否含有数组中的某项,如果没有该项则插入该项并赋值0
题干:
let arr = [“a”, “b”, “c”, “d”]
let obj = {a:12,b:13}
期望结果:res = {a:12, b:13, c:0, d:0}
Method 1:
arr.forEach(item => {
if (obj.hasOwnProperty(item)) {
obj[item] = obj[item]
} else {
obj[item] = 0
}
})
console.log(obj) // 输出结果:{a: "12", b: "13", c: 0, d: 0}
Method 2:
arr.forEach(item => obj[item] = item in obj ? obj[item] : 0)
console.log(obj) // 输出结果:{a: "12", b: "13", c: 0, d: 0}
Methods 3:
let res = arr.reduce((a, b) => ({ [b]: 0, ...a }), obj)
console.log(res) // 输出结果:{d: 0, c: 0, b: 13, a: 12}