假设我有两个对象数组作为,
let detail1 = [
{'book':'LOTR','price':'14'}
{'book':'Harry pottar','price':'12'},
]
let detail2 = [
{'book':'Harry pottar','price':'15'},
{'book':'LOTR','Price':'14'},
{'book':'HPP','Price':'21'}
]
我想比较两个对象数组,并根据它们是否相同返回true或false。
注意:对象的结构,即键将始终相同,它们的值可能会改变,也可能不会改变。
为此,我尝试了
for(let i = 0 ;i<detail1.length; i++){
for(let j = 0; j<detail2.length; j++){
if(JSON.stringify(detail1[i]) === JSON.stringify(detail2[i])){
boolValue = true
} else {
boolValue = false
}
}
}
但这给出了不正确的值,比如说我有另一个对象数组,
let detail1 = [
{'book':'LOTR','price':'14'}
{'book':'Harry pottar','price':'12'},
]
let detail2 = [
{'book':'Harry pottar','price':'12'},
{'book':'LOTR','price':'14'}
]
但当订单被更改时,它给出的值不正确。
在给定对象结构(即键相同)的任何情况下,比较两个对象数组并返回true(如果它们相同)和false(如果不同)的可能解决方案是什么。
您不能使用JSON编码来检查相等性,因为它依赖于顺序,例如:
console.log(
JSON.stringify({'book':'LOTR','price':'14'}) == JSON.stringify({'price':'14', 'book':'LOTR'})
)
然而,你可以这样做:
let detail1 = [
{'book':'LOTR','price':'14'},
{'book':'Harry pottar','price':'12'},
]
let detail2 = [
{'book':'Harry pottar','price':'15'},
{'book':'LOTR','Price':'14'},
{'book':'HPP','Price':'21'}
]
function equal(a, b){
return a.length == b.length && // same length and
a.every( // every element in a
e1 => b.some( // has a match in b
e2 => e1.book == e2.book && e1.price == e2.price
)
)
}
console.log(equal(detail1,detail2), equal(detail1,detail1), equal(detail2,detail2))
正如@T.J Crowder所指出的,你实际上可以避免手动检查对象的每个条目,只需使用Object.entries
(请注意,只有当你的对象仅由密钥对字符串组成时,才使用此选项)
let detail1 = [
{'book':'LOTR','price':'14'},
{'book':'Harry pottar','price':'12'},
]
let detail2 = [
{'book':'Harry pottar','price':'15'},
{'book':'LOTR','Price':'14'},
{'book':'HPP','Price':'21'}
]
function equal(a, b){
return a.length == b.length && // same length and
a.every( // every element in a
e1 => b.some( // has a match in b
e2 => Object.keys(e1).every(key => e1[key] === e2[key])
)
)
}
console.log(equal(detail1,detail2), equal(detail1,detail1), equal(detail2,detail2))
您可以使用Object.keys和每个轻松实现结果
arr1.length !== arr2.length &&
arr1.every((o, i) =>
Object.keys(o).every((prop) => arr2[i][prop] && arr2[i][prop] === o[prop])
)
let detail1 = [
{ book: "LOTR", price: "14" },
{ book: "Harry pottar", price: "12" },
];
let detail2 = [
{ book: "Harry pottar", price: "15" },
{ book: "LOTR", Price: "14" },
{ book: "HPP", Price: "21" },
];
function isEqual(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
return arr1.every((o, i) => {
return Object.keys(o).every((prop) => {
return arr2[i][prop] && arr2[i][prop] === o[prop];
});
});
}
console.log(isEqual(detail1, detail2));