js 数组组合的处理?

哈哈哈
  • 50
湖南
let a = [
 {
  name: '随便',
  childList: [
    name: '广州南沙'
  ]
 },
 {
  name: '随便1',
  childList: [
    name: '广州番禺'
  ]
 }
]

let b = [
 {
    name: '广州南沙',
    phone: '132XXXX5665',
    remark:'备注一'
 },
 {
    name: '广州番禺',
    phone: '132XXXX6666',
    remark:'备注二'
 }
]

需要得到:根据a数组下面的childList数组name属性相同的,把b数组的值加到a数组里面。

let c = [
  {
    name: '随便',
    childList: [
      name: '广州南沙',
      phone: '132XXXX5665',
      remark:'备注一'
    ]
  },
  {
    name: '随便1',
    childList: [
      name: '广州番禺',
      phone: '132XXXX6666',
      remark:'备注二'
    ]
  }
]
回复
阅读 1k
4 个回答
✓ 已被采纳

要处理的对象在 a 中的第二层,需要两个循环

a.forEach(({ childList }) => childList.forEach(
    it => Object.assign(it, b.find(({ name }) => name == it.name))
));

这里是直接在 b 中去找的对象。如果 b 中的内容不多,直接查找还是很快。

也可以把所有 childList 展平来处理(效率应该会低一些)

a.flatMap(({ childList }) => childList)
    .forEach(it => Object.assign(it, b.find(({ name }) => name == it.name)));

如果 b 中的内容比较多,先做映射表效率会更优

const bMap = Object.fromEntries(
    b.map(it => [it.name, it])
);

a.forEach(({ childList }) => childList.forEach(
    it => Object.assign(it, bMap[it.name])
));

先把b按name组装成字典,再遍历一遍childList刷新一下。

let a = [
 {
  name: '随便',
  childList: [
    {name: '广州南沙'}
  ]
 },
 {
  name: '随便1',
  childList: [
    {name: '广州番禺'}
  ]
 }
]

let b = [
 {
    name: '广州南沙',
    phone: '132XXXX5665',
    remark:'备注一'
 },
 {
    name: '广州番禺',
    phone: '132XXXX6666',
    remark:'备注二'
 }
]

const bMap = {}
b.forEach(item=>{
  bMap[item.name] = item
})

a.forEach(item=>{
  item.childList = item.childList.map(child=>{
    return bMap[child.name]
  })
})

console.log(a)
君泽
  • 98
谁家数组是这样写的
 childList: [
    name: '广州南沙'
  ]



let a = [
 {
  name: '随便',
  childList: [
    {name: '广州南沙'}
  ]
 },
 {
  name: '随便1',
  childList: [
    {name: '广州番禺'}
  ]
 }
]

let b = [
 {
    name: '广州南沙',
    phone: '132XXXX5665',
    remark:'备注一'
 },
 {
    name: '广州番禺',
    phone: '132XXXX6666',
    remark:'备注二'
 }
]

const bMap = {}
b.forEach(item=>{
  bMap[item.name] = item
})

a.forEach(item=>{
  item.childList = item.childList.map(child=>{
    return bMap[child.name]
  })
})

扬帆启航
  • 3.5k
let b = [
 {
    name: '广州南沙',
    phone: '132XXXX5665',
    remark:'备注一'
 },
 {
    name: '广州番禺',
    phone: '132XXXX6666',
    remark:'备注二'
 }
];
    var bMap = Object.fromEntries(b.map(item=>[item.name,item]))

let a = [
 {
  name: '随便',
  childList: [
      {name: '广州南沙'}
  ]
 },
 {
  name: '随便1',
  childList: [
      { name: '广州番禺'}
  ]
 }
]
var res = a.map(item=>{
    return Object.assign({}, item, {childList: item.childList.map(childItem=>{
        return Object.assign({}, childItem, bMap[childItem.name]||{})
    })
   })
})
console.log(res)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏