前言
js 数组对象的合并,方便自己后续使用与学习,废话少说,这段代码的功能就是根据某个相同的value值合并两个数组对象
比如:根据相同的hotelId
来合并
一 , 数组对象根据相同属性值合并两个对象
话不多说,直接上代码
const hotelList = [{
hotelId:'70931',
price:'350',
hotelName:'如家',
address:'西乡地铁站A口',
},{
hotelId:'70932',
price:'350',
hotelName:'如家',
address:'西乡地铁站A口',
},{
hotelId:'70933',
price:'350',
hotelName:'如家',
address:'西乡地铁站A口',
},{
hotelId:'70934',
price:'350',
hotelName:'如家',
address:'西乡地铁站A口',
}];
const hotelList1 = [{
hotelId:'70931',
price:'458',
hotelName:'如家'
},{
hotelId:'70932',
price:'360',
hotelName:'速8酒店'
},{
hotelId:'70933',
price:'850',
hotelName:'7天'
},{
hotelId:'70934',
price:'4250',
hotelName:'格林豪泰'
},{
hotelId:'70935',
price:'100',
hotelName:'如意宾馆'
},{
hotelId:'70936',
price:'1350',
hotelName:'中天美景大酒店'
}];
// 把数组hotelList1合并hotelList
const newArr = hotelList.map(hotelItem => {
const data = hotelList1.find(i => hotelItem.hotelId === i.hotelId)
return {
...hotelItem,
...data,
}
})
// 合并后的结果如下,正好是我想要的结果
console.log(newArr);
// (4) [{…}, {…}, {…}, {…}]
// 0: {hotelId: '70931', price: '458', hotelName: '如家', address: '西乡地铁站A口'}
// 1: {hotelId: '70932', price: '360', hotelName: '速8酒店', address: '西乡地铁站A口'}
// 2: {hotelId: '70933', price: '850', hotelName: '7天', address: '西乡地铁站A口'}
// 3: {hotelId: '70934', price: '4250', hotelName: '格林豪泰', address: '西乡地铁站A口'}
// length: 4
// [[Prototype]]: Array(0)
二 ,判断两个对象数组内的值是否相等
// 判断两个对象数组内的值是否完全相等
let arr1 = [{ "id": 1, "name": "张三" },{"id": 33, "name": "测试name"}];
let arr2 = [{ "id": 1, "name": "张三" }];
var data = JSON.stringify(arr1) === JSON.stringify(arr2);
console.log(data); //false