Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

对象合并问题

两个对象a覆盖b 相同字段替换 遇到数组 数组内id相同的覆盖

a = {
    name: '',
    age: '',
    obj:{
        one:'',
        two:''
    },
    count: [
      {
        id: 1,
        sex: ''
      },
      {
        id: 2,
        sex: ''
      },
      {
        id: 3,
        sex: ''
      },
      {
        id: 4,
        sex: ''
      }
    ]
  }
  
 b = {
    name: 'xxx',
    age: '13',
    obj:{
        one:'1',
        two:'2'
    },
    count: [
      {
        id: 2,
        sex: '22'
      },
      {
        id: 4,
        sex: '44'
      }
    ]
  }
  

期望得到的对象为

  
 c = {
    name: 'xxx',
    age: '13',
    obj:{
        one:'1',
        two:'2'
    },
    count: [
      {
        id: 1,
        sex: ''
      },
      {
        id: 2,
        sex: '22'
      },
      {
        id: 3,
        sex: ''
      },
      {
        id: 4,
        sex: '44'
      }
    ]
  } 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var a = {
    name: '',
    age: '',
    obj:{
        one:'',
        two:''
    },
    count: [
      {
        id: 1,
        sex: ''
      },
      {
        id: 2,
        sex: ''
      },
      {
        id: 3,
        sex: ''
      },
      {
        id: 4,
        sex: ''
      }
    ]
  }
  
var b = {
    name: 'xxx',
    age: '13',
    obj:{
        one:'1',
        two:'2'
    },
    count: [
      {
        id: 2,
        sex: '22'
      },
      {
        id: 4,
        sex: '44'
      }
    ]
  }
function merge(target, source) {
  if(Array.isArray(target)) {
    var indexes = target.reduce((res, item, index) => {
      res[item.id] = index;
      return res;
    }, {})
    source.forEach(item => {
      var index = indexes[item.id]
      target[index] = item;
    })
  } else {
    for(var key in source) {
      if(key in target) {
          if(Array.isArray(source[key])) merge(target[key], source[key])
        else target[key] = source[key]
      }
    }
  }
  return target;
}

merge(a, b)
  

这里如果target里没有该字段没有进行合并,如果需要可以自行修改下


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...