迭代2个对象数组并返回单个对象数组的有效方法是什么?
我想遍历exerxises数组,将每个object.id与searchResult的object.id进行比较,并在不重复的新数组中返回非相等的searchResult对象。
我遇到问题,因为两个数组的长度都不相同
const exercises = [
{
id: 'pull-ups',
title: 'Pull Ups',
description: 'Back and biceps exercise...',
muscles: 'back'
},
{
id: 'deadlifts',
title: 'Deadlifts',
description: 'Back and leg exercise...',
muscles: 'back'
},
{
id: 'squats',
title: 'Squats',
description: 'Legs exercise...',
muscles: 'legs'
}
]
const searchResult = [
{
id: 'overhead-press',
title: 'Overhead Press',
description: 'Delts exercise...',
muscles: 'shoulders'
},
{
id: 'dips',
title: 'Dips',
description: 'Triceps exercise...',
muscles: 'arms'
},
{
id: 'barbell-curls',
title: 'Barbell Curls',
description: 'Biceps exercise...',
muscles: 'arms'
},
{
id: 'bench-press',
title: 'Bench Press',
description: 'Chest exercise...',
muscles: 'chest'
},
{
id: 'pull-ups',
title: 'Pull Ups',
description: 'Back and biceps exercise...',
muscles: 'back'
},
{
id: 'deadlifts',
title: 'Deadlifts',
description: 'Back and leg exercise...',
muscles: 'back'
},
{
id: 'squats',
title: 'Squats',
description: 'Legs exercise...',
muscles: 'legs'
}
]
通过比较ID,我想从不同的btw练习和searchResult中返回一个新的Objects数组,而不重复!
答案 0 :(得分:0)
const exercises = [{id: 'pull-ups',title: 'Pull Ups',description: 'Back and biceps exercise...',muscles: 'back'},
{id: 'deadlifts',title: 'Deadlifts',description: 'Back and leg exercise...',muscles: 'back'},
{id: 'squats',title: 'Squats',description: 'Legs exercise...',muscles: 'legs'}]
const searchResult = [{id: 'overhead-press',title: 'Overhead Press',description: 'Delts exercise...',muscles: 'shoulders'},
{id: 'dips',title: 'Dips',description: 'Triceps exercise...',muscles: 'arms'},
{id: 'barbell-curls',title: 'Barbell Curls',description: 'Biceps exercise...',muscles: 'arms'},
{id: 'bench-press',title: 'Bench Press',description: 'Chest exercise...',muscles: 'chest'},
{id: 'pull-ups',title: 'Pull Ups',description: 'Back and biceps exercise...',muscles: 'back'},
{id: 'deadlifts',title: 'Deadlifts',description: 'Back and leg exercise...',muscles: 'back'},
{id: 'squats',title: 'Squats',description: 'Legs exercise...',muscles: 'legs'}]
let op = searchResult.reduce((op,inp) => {
let add = exercises.find(e=> e.id === inp.id)
if(!add){
op[inp.id] = inp
}
return op
},{})
console.log(Object.values(op))