gpt4 book ai didi

javascript - 过滤数组并获取第一个值作为唯一 id 的对象数组

转载 作者:行者123 更新时间:2023-12-02 17:29:53 39 4
gpt4 key购买 nike

我有以下数组例如,我只需要返回唯一 ID,因为在这个数组中我有两次 id 1 和 3 我需要仅包含第一个 findigs id 的新数组,

在此示例中,前 3 个条目,我如何将其与映射/过滤器一起使用,而不是与常规 for 一起使用

var oData = [{
id: 1,
ListTypeGroupDescription: 2,
test: 111,
test2: 222
}, {
id: 2,
ListTypeGroupDescription: 4,
test: 333,
test2: 444
}, {
id: 3,
ListTypeGroupDescription: 6,
test: 666,
test2: 777
}, {
id:1,
ListTypeGroupDescription: 99,
test: 666,
test2: 777
}, {
id: 3,
ListTypeGroupDescription: 99,
test: 666,
test2: 777
}];


var data = oData.map(
function(obj) {
return obj.id;
}
);

http://jsfiddle.net/5qu0j8g0/1/

map 仅返回 ID,但我需要所有对象

我需要这个新数组

var oNew = [{
id: 1,
ListTypeGroupDescription: 2,
test: 111,
test2: 222
}, {
id: 2,
ListTypeGroupDescription: 4,
test: 333,
test2: 444
}, {
id: 3,
ListTypeGroupDescription: 6,
test: 666,
test2: 777
}
]

最佳答案

您可以使用 Array#filter 进行过滤和一个临时哈希表 Object.create(null))(一个没有任何原型(prototype)的空对象),位于使用 this 寻址的回调中。

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var oData = [{ id: 1, ListTypeGroupDescription: 2, test: 111, test2: 222 }, { id: 2, ListTypeGroupDescription: 4, test: 333, test2: 444 }, { id: 3, ListTypeGroupDescription: 6, test: 666, test2: 777 }, { id: 1, ListTypeGroupDescription: 99, test: 666, test2: 777 }, { id: 3, ListTypeGroupDescription: 99, test: 666, test2: 777 }],
oNew = oData.filter(function (a) {
if (!this[a.id]) {
this[a.id] = true;
return true;
}
}, Object.create(null));

console.log(oNew);

ES6

var oData = [{ id: 1, ListTypeGroupDescription: 2, test: 111, test2: 222 }, { id: 2, ListTypeGroupDescription: 4, test: 333, test2: 444 }, { id: 3, ListTypeGroupDescription: 6, test: 666, test2: 777 }, { id: 1, ListTypeGroupDescription: 99, test: 666, test2: 777 }, { id: 3, ListTypeGroupDescription: 99, test: 666, test2: 777 }],
oNew = oData.filter((temp => a => !temp[a.id] && (temp[a.id] = true))(Object.create(null)));

console.log(oNew);

关于javascript - 过滤数组并获取第一个值作为唯一 id 的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37696082/

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