js检查对象是否含有数组中的某项

CaixK
  • 366

如何判断对象是否含有数组中的某项,如果没有该项则插入该项并赋值0

arr = ["viapadDlOpt", "viapadDlMin", "pthpadDlOpt", "cuOz"]
obj = {
    viapadDlOpt:12,
    viapadDlMin:13
}

res = {
    viapadDlOpt:12,
    viapadDlMin:13,
    pthpadDlOpt:0,
    cuOz:0
}

回复
阅读 820
4 个回答
arr.forEach(k => obj[k] ??= 0)

更兼容的版本

arr.forEach(k => {
    if (! k in obj) obj[k] = 0
})
let obj = {
  a:'this is a',
  b:'this is b',
}
let arr = ['a','b','c','d'];

arr.forEach(item => obj[item] = item in obj ? obj[item] : 0)

console.log(obj)
const arr = ["viapadDlOpt", "viapadDlMin", "pthpadDlOpt", "cuOz"]
const obj = {
    viapadDlOpt:12,
    viapadDlMin:13
}

const res = arr.reduce((a,b) => ({[b]:0,...a}),obj)

如果只是检查一次可以用楼上的,如果检查多次可以用Object.assign 或者展开符。

const arr = ["viapadDlOpt", "viapadDlMin", "pthpadDlOpt", "cuOz"]
const emptyArr = {}
arr.forEach(item=>(emptyArr[item] = 0))
let obj = {
    viapadDlOpt:12,
    viapadDlMin:11
}
let res = {
    viapadDlOpt:12,
    viapadDlMin:13,
    pthpadDlOpt:0,
    cuOz:0
}
let newObj = Object.assign({},emptyArr,obj)
// newObj=>{viapadDlOpt: 12, viapadDlMin: 11, pthpadDlOpt: 0, cuOz: 0}
let newRes = {...emptyArr,...res}
// newRes=>{viapadDlOpt: 12, viapadDlMin: 13, pthpadDlOpt: 0, cuOz: 0}
你知道吗?

宣传栏