js如何把b数组的元素放到相对应a数组里?

a数组:

[{ id: 1, key: 'key1', value: 'ggg' }, { id: 2, key: 'key2', value: 'cccc' }]

b数组

{ id: 4, key1: '123', key2: 'sdfdff' }

期望

[
    { id: 1, key: 'key1', value: 'ggg', key1: '123' },
    { id: 2, key: 'key2', value: 'cccc', key2: 'sdfdff' }
]
阅读 1.8k
2 个回答
let arr1= [{id:1,key:'key1',value:'ggg'},{id:2,key:'key2',value:'cccc'}]
let obj1 = {id:4,key1:'123',key2:'sdfdff'}
arr1.forEach(item=>{
    item[item.key] = obj1[item.key];
})

应该使用 hash table 提升效率

const arrA = [{ id: 1, key: 'key1', value: 'ggg' }, { id: 2, key: 'key2', value: 'cccc' }]
const arrB = { id: 4, key1: '123', key2: 'sdfdff' }
const bHash = Object.fromEntries(
    Object.entries(arrB).filter(
        ([key]) => key.startsWith(key)
    ).map(([key, value]) => [key, value])
)

arrA.forEach(item => {
    item[item.key] = bHash[item.key]
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题