JavaScript 比较两个 JSON 文件并仅输出新对象



我想比较两个JSON文件,并根据它们的"Id"仅输出新添加的对象。我还需要忽略 JSON 文件中对象位置的变化(我不想比较行变化(。

您会在下面的代码中注意到 Lege 的年龄发生了变化 - 我也不想在我的输出中包含这些(Key:Value(更改。

我目前正在使用一个名为json-diff的软件包。

这是我当前的代码:

const jsonDiff = require('json-diff');
var oldJson = {
"data": [ 
{
"Id": "2",
"Name": "Greg",
"ranges": [
{
"age": "70"
}
]
},
{
"Id": "1",
"Name": "Tom",
"ranges": [
{
"age": "10"
}
]
}
]
};
var newJson = {
"data": [
{
"Id": "2",
"Name": "Greg",
"ranges": [
{
"age": "20" // Even though Greg's age has changed, I don't want it in my output
}
]
},
{
"Id": "3",
"Name": "Bob",
"ranges": [
{
"age": "30"
}
]
},  
{
"Id": "1",
"Name": "Tom",
"ranges": [
{
"age": "10"
}
]
}
]
};
function compare(newJson, oldJson) {
let rawDiff = jsonDiff.diff(newJson.data, oldJson.data);
let prettyDiff = JSON.stringify(rawDiff).replace(/,[" "]/g, '');
console.log(prettyDiff);
}
compare(newJson, oldJson);

电流输出:

[
[
"~",
{
"ranges": [
[
"-",
{
"age": "20"
}
],
[
"+",
{
"age": "70"
}
]
]
}
],
[
"-",
{
"Id": "3",
"Name": "Bob",
"ranges": [
{
"age": "30"
}
]
}
]
]

所需输出:

{
"data": [
{
"Id": "3",
"Name": "Bob",
"ranges": [
{
"age": "30"
}
]
}
]
}

我不确定这是否是你的需要,但是

var oldJson = {
"data": [ 
{ "Id": "2", "Name": "Greg", "ranges": [ { "age": "70" } ] },
{ "Id": "1", "Name": "Tom", "ranges": [ { "age": "10" } ] }
]
};
var newJson = {
"data": [
{ "Id": "2", "Name": "Greg", "ranges": [ { "age": "20" } ] },
{ "Id": "3", "Name": "Bob", "ranges": [ { "age": "30" } ] },  
{ "Id": "1", "Name": "Tom", "ranges": [ { "age": "10" } ] }
]
};
function compare(newJson, oldJson) {
// get Id's from oldJson
let ids = oldJson.data.map(ch => ch.Id);
// filter from newJson that's not inside from old ids
return newJson.data.filter(ch => !ids.includes(ch.Id));
}
console.log(compare(newJson, oldJson)); // [ { Id: '3', Name: 'Bob', ranges: [ [Object] ] } ]

对于那些需要解决更复杂的问题的人:

function compareJsonArrays(currentArray, newArray) {
const diff = {
newItems: [],
deletedItems: [],
updatedItems: []
};
const currentSet = new Set(currentArray.map(item => item.id));
const newSet = new Set(newArray.map(item => item.id));
for (const element of newArray) {
if (!currentSet.has(element.id)) {
diff.newItems.push(element);
} else {
const currentItemIndex = currentArray.findIndex(item => item.id === element.id);
if (!compareObjects(element, currentArray[currentItemIndex])) {
diff.updatedItems.push(element);
}
}
}
for (const element of currentArray) {
if (!newSet.has(element.id)) {
diff.deletedItems.push(element);
}
}
return diff;
}
function compareObjects(obj1, obj2) {
return JSON.stringify(obj1) === JSON.stringify(obj2);
}

相关内容

  • 没有找到相关文章

最新更新