gpt4 book ai didi

javascript - jQuery:打印数组中一组重复对象中的第一个对象

转载 作者:行者123 更新时间:2023-11-27 23:36:15 25 4
gpt4 key购买 nike

我有一个像这样的数组:

var json.result= [
{"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"},
{"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"},
{"id":"2","category":"Camera","name":"7D Kit", "condition":"OK"},
{"id":"3","category":"Camera","name":"7D Kit", "condition":"OK"}]

我正在尝试执行以下操作:1/找到所有“名字”2/当发现重复的“name”时,只打印第一个对象

因此结果将是:
设备id:0
类别:相机
名称:600D套件

设备 ID:2
类别:相机
名称:7D套件

以下是我的尝试:

json.result.map(function(equipment){

var equipmentNamesArray = equipment.name;
var arr = $.makeArray(equipmentNamesArray);

var uniqueNames = equipmentNamesArray.reduce(function(a,b){
if (a.indexOf(b) < 0) a.push(b);
}, equipmentNamesArray);
console.log("equipment ID: ", uniqueNames.id);
console.log("category: ", uniqueNames.category);
console.log("name: ", uniqueNames);
});

但是,我遇到了 TypeError: EquipmentNamesArray.reduce is not a function 错误。如果有人能告诉我哪一部分逻辑做错了,我将不胜感激:)))

干杯,凯伦

最佳答案

这是您需要的代码:

JSFiddle

var json = [], equipmentNamesArray = [];

json.result= [
{"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"},
{"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"},
{"id":"2","category":"Camera","name":"7D Kit", "condition":"OK"},
{"id":"3","category":"Camera","name":"7D Kit", "condition":"OK"}];

json.result.map(function(equipment) {
if ($.inArray(equipment.name, equipmentNamesArray) === -1) {
console.log(equipment);
equipmentNamesArray.push(equipment.name);
}
});

您必须创建 equipmentNamesArray 数组来包含在其他所有内容之前检查的项目,当您开始迭代主 result 数组时,您将检查 equipment. name 已在 equipmentNamesArray 数组中。

如果它不在数组中,则打印它并将其推送到数组中。

那么下一个将被跳过,因为它还包含在 equipmentNamesArray 数组中。

这是另一个版本,进行了更改以保留仅包含您想要的项目的新数组:JSFiddle 2

关于javascript - jQuery:打印数组中一组重复对象中的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34116360/

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