-
慕容3067478
一种快速的方法是同时对people数组进行字符串化并检查字符串中的位置。这免除了您遍历嵌套结构的麻烦。var positions = [{ val: 'CEO', label: 'CEO XXX' }, { val: 'CTO', label: 'CTO XXX' }, { val: 'CBO', label: 'CBO XXX' }, { val: 'CLO', label: 'CLO XXX' }]var people = [{ id: 'AAA', positions: [{ val: 'CEO', label: 'CEO XXX' }] }, { id: 'BBB', positions: [{ val: 'CXO', label: 'CXO XXX' }, { val: 'CEO', label: 'CEO XXX' }] }, { id: 'CCC', positions: [{ val: 'CTO', label: 'CTO XXX' }] }];var stringifiedPeople = JSON.stringify(people)var newPositions = positions.filter((position) => !stringifiedPeople.includes(JSON.stringify(position)));console.log(newPositions)或者,您可以创建一个包含所有占用位置的地图,并过滤掉可用的位置。var positions = [{ val: 'CEO', label: 'CEO XXX' }, { val: 'CTO', label: 'CTO XXX' }, { val: 'CBO', label: 'CBO XXX' }, { val: 'CLO', label: 'CLO XXX' }]var people = [{ id: 'AAA', positions: [{ val: 'CEO', label: 'CEO XXX' }] }, { id: 'BBB', positions: [{ val: 'CXO', label: 'CXO XXX' }, { val: 'CEO', label: 'CEO XXX' }] }, { id: 'CCC', positions: [{ val: 'CTO', label: 'CTO XXX' }] }];var mappedPositions = {}people.forEach((p) => p.positions.forEach((position) => mappedPositions[position.val] = true ));var newPositions = positions.filter((position) => !mappedPositions[position.val]);console.log(newPositions)
-
PIPIONE
执行我的评论。为了.reduce()提高效率,可以将整个事情写成一个很大的数组,但是我更喜欢显示确切的步骤,以使每个步骤的工作更加清晰。var positions = [{val:'CEO',label:'CEOXXX'},{val:'CTO',label:'CTOXXX'},{val:'CBO',label:'CBOXXX'},{val:'CLO',label:'CLOXXX'}];var people = [{id:'AAA',positions:[{val:'CEO',label:'CEOXXX'}]},{id:'BBB',positions:[{val:'CXO',label:'CXOXXX'},{val:'CEO',label:'CEOXXX'}]},{id:'CCC',positions:[{val:'CTO',label:'CTOXXX'}]}];const occupied_positions = people .map( person => person.positions ) .flat() .map( position => position.val ); const all_positions = positions .map( position => position.val ); const open_positions = all_positions .filter( position => !occupied_positions.includes( position )) .map( position => positions.find( source => source.val === position )); console.log( open_positions );
-
缥缈止盈
您可以使用filter,find和some过滤掉那些不在people数组的positions数组中的对象。var positions = [{val:'CEO',label:'CEOXXX'},{val:'CTO',label:'CTOXXX'},{val:'CBO',label:'CBOXXX'},{val:'CLO',label:'CLOXXX'}];var people = [{id:'AAA',positions:[{val:'CEO',label:'CEOXXX'}]},{id:'BBB',positions:[{val:'CXO',label:'CXOXXX'},{val:'CEO',label:'CEOXXX'}]},{id:'CCC',positions:[{val:'CTO',label:'CTOXXX'}]}];const out = positions.filter(position => { return !people.find(person => { return person.positions.some(({ val, label }) => { return val === position.val && label === position.label; }); });});console.log(out);