gpt4 book ai didi

Javascript:根据多个键确定并返回对象数组中的重复对象

转载 作者:行者123 更新时间:2023-12-03 03:58:54 25 4
gpt4 key购买 nike

我有一个对象数组:

    var data  = [{"monitor":"TFT",
"manufacturer":"MONCORP",
"monID":"1234",
"Delivery Way":"DELIVERY",
"BarCode Text":"Test",
"BarCode Id":"D9",
"Status":"OK"},

{"monitor":"LCD",
"manufacturer":"MONCORP",
"monID":"",
"Delivery Way":"PICKUP",
"BarCode Text":"Dummy Text",
"BarCode Id":"P2",
"Status":"OK"},

{"monitor":"TFT",
"manufacturer":"MONCORP",
"monID":"1234",
"Delivery Way":"DELIVERY",
"BarCode Text":"ONLY TEST",
"BarCode Id":"D9",
"Status":"OK"},

{"monitor":"LCD",
"manufacturer":"MONCORP",
"monID":"1234",
"Delivery Way":"DELIVERY",
"BarCode Text":"FOR TESTING PURPOSE",
"BarCode Id":"D9",
"Status":"OK"},

{"monitor":"TFT",
"manufacturer":"MONCORP",
"monID":"",
"Delivery Way":"PICKUP",
"BarCode Text":"DUMMIEST TEXT",
"BarCode Id":"P7",
"Status":"OK"}];

所以我只想获取重复的对象,但我想根据键值来区分它们:监视器、制造商、monID​​、送货方式、条形码 Id、状态。

预期结果是:

    expected = [{"monitor":"TFT",
"manufacturer":"MONCORP",
"monID":"1234",
"Delivery Way":"DELIVERY",
"BarCode Text":"Test",
"BarCode Id":"D9",
"Status":"OK"},

{"monitor":"TFT",
"manufacturer":"MONCORP",
"monID":"1234",
"Delivery Way":"DELIVERY",
"BarCode Text":"ONLY TEST",
"BarCode Id":"D9",
"Status":"OK"}]

最佳答案

在数据库级别执行此操作可能是个好主意(例如某种 GROUP BY 操作)。

在 JavaScript 中,您可以迭代数组并为每个记录创建一个哈希值,该哈希值应由您希望唯一的字段组成。然后,该哈希值可以用作映射键,即将这些记录插入具有该键的映射中将消除重复项。

示例:

var map = {};
for (var i = 0; i < data.length; i++) {
var key = data[i].monitor + "#" + data[i].monID + "#" + data[i].manufacturer + ... ;
map[key] = data[i];
}

map 对象最后将仅包含映射到具有该键的最后项的唯一键。

请注意,key 只是一个由您希望唯一的字段连接而成的字符串。如果您的字段包含字符 #,或者它们不是字符串类型,则它无法正常工作。如果你想走这条路,我建议计算 hash code from the string

识别重复项,您可以在迭代的每个步骤中检查是否已在 map 中:

if (map[key]) {
// This record is a duplicate
}

为了将重复记录分组在一起,您可以构造一个映射映射键 -> 重复项数组。可以这样完成(仅显示循环内部)

var key = ...
if (!map[key]) {
// First time we see this key, let's add it to the map
map[key] = [ data[i] ]; // Map the key to a new array containing the current record
} else {
// Duplicate; just add this record to the existing
// list of records with the same key
map[key].push(data[i]);
}

关于Javascript:根据多个键确定并返回对象数组中的重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44820519/

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