【问题标题】:How to compare each element in array to one single value? [duplicate]如何将数组中的每个元素与一个值进行比较? [复制]
【发布时间】:2019-01-28 22:23:43
【问题描述】:

我有一个array,里面有多个objects。 它的结构是这样的:

const Instructor = [
  { ID: '141',
    InstructorNameAR: 'test',
    InstructorNameEN: 'Mohamed Ahmed',
    InstructorBriefAR: 'phd in chemistry',
    InstructorBriefEN: 'phd in chemistry' },
  { ID: '140',
    InstructorNameAR: 'test',
    InstructorNameEN: 'Mahmoud Ahmed',
    InstructorBriefAR: 'phd in chemistry',
    InstructorBriefEN: 'phd in chemistry' },
]

我想添加其他 objects,但根据它们的 ID 值过滤了重复项。

objects 的示例我想添加:-

  const InstructorInstance = {
    ID: 'ID',
    InstructorNameAR:   'NAMEAR',
    InstructorNameEN:   'NAMEEN',
    InstructorBriefAR:  'BRIEFAR',
    InstructorBriefEN : 'BRIEFEN'
  }

我用这个方法过滤ID。 但它不起作用,因为它仅将arraysingle 值与我提供的值进行比较。这意味着它可能是一个duplicated object,但仍然会被添加,因为它没有检查它是否存在于每个array element

Instructor.forEach(instance =>{
  if(instance.ID !== InstructorInstance.ID){
    Instructor.push(InstructorInstance);
  }else{
    console.log('Duplicate')
  }
})

【问题讨论】:

  • 那么您心中的理想比较方式是什么?检查所有字段(区分大小写/不区分大小写)?如果是这样,为什么不简单地添加支票?

标签: javascript arrays object javascript-objects


【解决方案1】:

你必须先循环整个数组,然后再决定是否有重复。您可以为此使用 forEach,但 everysome 似乎非常适合这种工作:

const test = Instructor.every(instance => instance.ID !== InstructorInstance.ID);
if(test) {
    Instructor.push(InstructorInstance);
}

这意味着如果Instructor 中的每个对象的IDInstructorInstance 不同,则将InstructorInstance 推入Instructor

注意:您可以将测试直接放在if 中,而不必将其存储在变量test 中:

if(Instructor.every(instance => instance.ID !== InstructorInstance.ID)) {
    Instructor.push(InstructorInstance);
}

但这看起来不像,是吗?

【讨论】:

  • 成功了。谢谢!
  • 不客气!
【解决方案2】:

您可以使用some 来检查该对象是否已经存在,如果不存在,则添加它:

if (!Instructor.some(i => i.ID == instance.ID)) {
    Instructor.push(instance);
}

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    相关资源
    最近更新 更多