我有一群学生,我想创建一个独特的学生阵列。每个学生都有一个唯一的id值,我想与这个id值进行比较。
这是一个Student对象;
RestrictedDocument
答案 0 :(得分:2)
var Students =[
{
"id" : "3232aab1" //some other properties
} ,
{
"id" : "3232aab1" //some other properties
},
{
"id" : "3232aab2" //some other properties
} ,
{
"id" : "3232aab3" //some other properties
} ,
{
"id" : "3232aab2" //some other properties
} ];
var tmpObj = {};
var uniqArray = Students.reduce(function(acc,curr){
if (!tmpObj[curr.id]){
tmpObj[curr.id] = true;
acc.push(curr)
}
return acc;
},[]);
console.log(uniqArray);

答案 1 :(得分:1)
var a=[];
a.push({id:1,name:"something"});
// repeat similar;
访问ID
a[index].id;
要搜索的示例代码
var elem = 1; // id to be searched
//loop
for(var i=0; i<a.length; i++){
if(elem == a[i].id){
break;
}
}
// now a[i] will return the required data {id:1,name:"something"}
// a[i].id = > 1 and a[i].name => something
答案 2 :(得分:0)
我可能采取与此类似的方法......
class Students extends Map {
set(key, value) {
if (this.has(key)) { throw new Error('Student already there'); }
return super.set(key, value);
}
}
const students = new Students();
students.set(1, { name: 'Peter' });
console.log(students.get(1));
// students.set(1, { name: 'Gregor' }); this throws
答案 3 :(得分:-1)
如果您有下划线,则可以使用以下
ES6
_.uniq(Students, student=>student.id)
ES5
_.uniq(Students, function(student){return student.id;})