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.1k views
in Technique[技术] by (71.8m points)

两个对象数组对比,如果有相同的项就删除,不同就添加

两个对象数组对比,如果有相同的项就删除,不同就添加

var a =[{id: 1,content:'11'},{id: 2, content:'22'},{id: 3, content: '33'}]
var b = []
// 这个时候 a和b不同 我要把a数组的3个对象添加进b数组 得到
b = [{id: 1,content:'11'},{id: 2, content:'22'},{id: 3, content: '33'}]


var a =[{id: 1,content:'11'},{id: 2, content:'22'},{id: 3, content: '33'}]
var b = [{id: 1,content:'11'},{id: 2, content:'22'},{id: 3, content: '33'}]
// 这个时候 a和b相同 
//我需要把b数组中的所有相同项全部删除 得到
b = []

var a =[{id: 1,content:'11'},{id: 2, content:'22'},{id: 3, content: '33'}]
var b = [{id: 1,content:'11'},{id: 2, content:'22'}]
// 这个时候 a和b有相同项和不同项 
// 我需要把b数组中的相同项删除 不同项添加进去 得到
b = [{id: 3, content: '33'}]

请大佬帮帮忙


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

1 Answer

0 votes
by (71.8m points)

针对这个问题,可以分步来解决,首先取出a中与b不相同的项,可以通过[].filter来找出这些元素,之后再取出b中与a中不同的项,将这两个的结果进行合并,即为所求。
参考:

a.filter((i) => !b.find((j) => j.id === i.id)).concat(
  b.filter((i) => !b.find((j) => j.id === i.id))
)

首先 a.filter((i) => !b.find((j) => j.id === i.id))筛选出a中与b中不同的元素,之后b.filter((i) => !b.find((j) => j.id === i.id))筛选出b中与a中不同的元素,之后concat合并两个结果


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

2.1m questions

2.1m answers

60 comments

57.0k users

...