比较两个JSON对象或数组中的值可以使用以下方法:
function compareJSON(obj1, obj2) {
// 比较两个JSON对象或数组
if (typeof obj1 !== typeof obj2) {
return false;
}
if (Array.isArray(obj1)) {
if (obj1.length !== obj2.length) {
return false;
}
for (let i = 0; i < obj1.length; i++) {
if (!compareJSON(obj1[i], obj2[i])) {
return false;
}
}
} else if (typeof obj1 === 'object') {
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
if (!compareJSON(obj1[key], obj2[key])) {
return false;
}
}
} else {
if (obj1 !== obj2) {
return false;
}
}
return true;
}
const json1 = {
"name": "John",
"age": 30,
"hobbies": ["reading", "coding"]
};
const json2 = {
"name": "John",
"age": 30,
"hobbies": ["reading", "coding"]
};
console.log(compareJSON(json1, json2)); // 输出: true
function compareJSON(obj1, obj2) {
const str1 = JSON.stringify(obj1);
const str2 = JSON.stringify(obj2);
return str1 === str2;
}
const json1 = {
"name": "John",
"age": 30,
"hobbies": ["reading", "coding"]
};
const json2 = {
"name": "John",
"age": 30,
"hobbies": ["reading", "coding"]
};
console.log(compareJSON(json1, json2)); // 输出: true
这两种方法都可以比较JSON对象或数组中的值,你可以选择适合你场景的方法来使用。