使用属性过滤两个json数组

时间:2018-05-28 11:08:43

标签: javascript arrays

如果使用类型script / javascript

在第二个数组中存在相同的对象,我必须过滤第一个数组

这是我的数组

var students = [{id: 1, name : 'SSS'},
{id: 2, name : 'SSa'},
{id: 3, name : 'SSb'},
{id: 4, name : 'SSc'},
{id: 5, name : 'SSd'}];

var emp = [{id: 1, name : 'SSS'},
{id: 4, name : 'SSc'},
{id: 5, name : 'SSd'}];

输出应为

var finalarr = [{id: 2, name : 'SSa'},
{id: 3, name : 'SSb'}]

我在下面尝试但产生了错误的输出

for (let i = 0; i < students.length; i++) {
    for (let j = 0; j < emp.length; j++) {
    if (students[i].id != emp[j].id) {
    finalarr.push(students[i]);
    }
}
}
console.log(finalarr);

//下面是我的实际应用程序代码

this.appointmentTypes.filter((data, index) => this.typesData.includes(this.typesData[index].appointmentType.id))

3 个答案:

答案 0 :(得分:5)

对象是对内存位置的引用 - 除非它们引用相同的内存位置,否则它们之间永远不会===,因此includes无法工作。迭代整个数组并测试名称和ID:

&#13;
&#13;
var students=[{id:1,name:'SSS'},{id:2,name:'SSa'},{id:3,name:'SSb'},{id:4,name:'SSc'},{id:5,name:'SSd'}]
var emp=[{id:1,name:'SSS'},{id:4,name:'SSc'},{id:5,name:'SSd'}]

const finalArr = students.filter(({ id, name }) =>
  !emp.some(exclude => exclude.id === id && exclude.name === name)
);
console.log(finalArr);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你的命令性尝试w /循环失败,因为你在找到具有不同id的第一个项目时推送到最终数组。

应该是

&#13;
&#13;
var students = [{id: 1, name : 'SSS'},
{id: 2, name : 'SSa'},
{id: 3, name : 'SSb'},
{id: 4, name : 'SSc'},
{id: 5, name : 'SSd'}];

var emp = [{id: 1, name : 'SSS'},
{id: 4, name : 'SSc'},
{id: 5, name : 'SSd'}];

var finalarr = []

for (let i = 0; i < students.length; i++) {
    let found = false // flag
    
    for (let j = 0; j < emp.length && !found; j++) {
      found = students[i].id === emp[j].id
    }
    
    if (!found) finalarr.push(students[i])
}

console.log(finalarr)
&#13;
&#13;
&#13;

但更好的选择是从第二个数组创建Set个ID。 new Set(emp.map(item => item.id))并使用filter(item => !set.has(item.id))

简单地过滤掉第一个数组中所有ID的元素

&#13;
&#13;
var students = [{id: 1, name : 'SSS'},
{id: 2, name : 'SSa'},
{id: 3, name : 'SSb'},
{id: 4, name : 'SSc'},
{id: 5, name : 'SSd'}];

var emp = [{id: 1, name : 'SSS'},
{id: 4, name : 'SSc'},
{id: 5, name : 'SSd'}];

console.log(
  students.filter(
    (set => item => !set.has(item.id))(new Set(emp.map(item => item.id)))
  )
)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

SetMap往往非常适合解决过滤问题。

有关详细信息,请参阅下文

// Input.
const students = [{id: 1, name : 'SSS'},{id: 2, name : 'SSa'},{id: 3, name : 'SSb'},{id: 4, name : 'SSc'},{id: 5, name : 'SSd'}]
const emp = [{id: 1, name : 'SSS'},{id: 4, name : 'SSc'},{id: 5, name : 'SSd'}]

// Filter.
const filter = (A, B) => {
  const set = new Set(B.map(JSON.stringify))
  return A.filter(x => !set.has(JSON.stringify(x)))
}

// Output.
const output = filter(students, emp)

// Proof.
console.log(output)