1 回答
TA贡献1775条经验 获得超11个赞
您可以扩展Object.entries()of object_a,过滤掉(使用Array.prototype.filter())那些在of中看不到的( Array.prototype.some()):Object.values() idobject_b
const a = {100:"Stack Overflow",101:"MDN Web Docks",102:"Javascript"},
b = {0:{id:100,name:'Stack',lastname:'Overflow',},1:{id:101,name:'Web',lastname:'Docks',}},
result = Object.fromEntries(
Object
.entries(a)
.filter(([key]) =>
Object
.values(b)
.some(({id}) => id == key)
)
)
console.log(result)
另一种方法(我猜可能工作得更快)可以Array.prototype.reduce()用来遍历并执行相同的检查Object.keys():object_a
const a = {100:"Stack Overflow",101:"MDN Web Docks",102:"Javascript"},
b = {0:{id:100,name:'Stack',lastname:'Overflow',},1:{id:101,name:'Web',lastname:'Docks',}},
result = Object
.keys(a)
.reduce((acc, key) => {
if(Object.values(b).some(({id}) => id == key))
acc[key]=a[key]
return acc
}, {})
console.log(result)
添加回答
举报