gpt4 book ai didi

javascript - 在两个 JavaScript 哈希中查找差异(添加和删除对)的最有效方法

转载 作者:行者123 更新时间:2023-11-28 21:24:21 24 4
gpt4 key购买 nike

我有两个 JavaScript 字符串哈希值,对象称为“existingItems”和“newItems”。我想比较和提取哪些项目已添加(对于 newItems 是唯一的)和哪些已被删除(对于现有项目是唯一的)。我希望比较是在每对的关键上。

最有效的方法是什么?我应该先对元素进行分类吗?我应该提取数组的键并单独使用它们吗?

哈希值示例:

var existing = [];
existing.push(["456",{Ref:"456",Title:"ttt456",food:"soup"}]);
existing.push(["789",{Ref:"789",Title:"ttt789",color:"blue",duck:"sauce"}]);
existing.push(["abc",{Ref:"abc",Title:"tttabc",colour:"yellklow",duck:"sauce"}]);
existing.push(["xyz",{Ref:"xyz",Title:"tttabc",colour:"yellklow",duck:"sauce"}]);
existing.push(["123",{Ref:"123",Title:"ttt123",pet:"cat"}]);

var newits = [];
newits.push(["abc",{Ref:"abc",Title:"tttabc",food:"horse"}]);
newits.push(["456",{Ref:"456",Title:"ttt456",pet:"cat",color:"green",cat:"sauce"}]);
newits.push(["def",{Ref:"def",Title:"tttabc",noise:"moo"}]);


var itemsAdded = compareHash(existing,newits);
var itemsRemoved =compareHash(newits,existing);

最佳答案

这些不是哈希值,而是数组! (在 Javascript 中,对象是哈希值)。

如果你像这样重写它们,可以更有效地完成:

var existing = {};
existing["456"] = {Ref:"456",Title:"ttt456",food:"soup"};
existing["789"] = {Ref:"789",Title:"ttt789",color:"blue",duck:"sauce"};
existing["abc"] = {Ref:"abc",Title:"tttabc",colour:"yellklow",duck:"sauce"};
existing["xyz"] = {Ref:"xyz",Title:"tttabc",colour:"yellklow",duck:"sauce"};
existing["123"] = {Ref:"123",Title:"ttt123",pet:"cat"};

var newits = {};
newits["abc"] = {Ref:"abc",Title:"tttabc",food:"horse"};
newits["456"] = {Ref:"456",Title:"ttt456",pet:"cat",color:"green",cat:"sauce"};
newits["def"] = {Ref:"def",Title:"tttabc",noise:"moo"};

var itemsAdded = compareHash(existing,newits);
var itemsRemoved =compareHash(newits,existing);

现在您可以检查 newits 中是否存在“abc”,如下所示:

if (newits.hasOwnProperty('abc')) {
// do what you need to do
}

循环访问对象中的属性(它们已经变成这样)——并回答您的问题:

function compareHash(oldObj, newObj) {
var result = {};
for (var key in newObj) {
if (newObj.hasOwnProperty(key)) { // filter in case someone else has added properties to the global Object prototype
if (!oldObj.hasOwnProperty(key)) {
result[key] = newObj[key];
}
}
}
return result;
}

关于javascript - 在两个 JavaScript 哈希中查找差异(添加和删除对)的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5431382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com