gpt4 book ai didi

javascript - 从javascript中的2个数组对象中获取不匹配的数据

转载 作者:搜寻专家 更新时间:2023-11-01 05:03:18 27 4
gpt4 key购买 nike

我有数组,1 个数组是主数据,另一个数组包含管道分隔值。请在下面找到相同的代码

var master = [
{id:1, value:'John'},
{id:2, value:'Bobby'}
];

var names = [
{id:1, name:'Sandra|John', type:'user', username:'sandraJ'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter|John', type:'user', username:'peteJ'},
{id:4, name:'Bobby', type:'user', username:'be_bob'},
{id:4, name:'Peter1|John1', type:'user', username:'be_bob'}
];

结果输出应该如下

var result3 = [
{id:1, name:'Sandra'},
{id:2, name:'Peter'},
{id:2, name:'Peter1|John1'}
];

我尝试了以下 ES6 版本,但它没有抛出预期的输出。

let result = names.filter(o1 => !master.some(o2 => 
o1.name.split('|').includes(o2.value)));

我也试过把some换成every,还是不行

let result = names.filter(o1 => !master.every(o2 => 
o1.name.split('|').includes(o2.value)));

有人可以帮我做同样的事情吗?

最佳答案

这确实假设结果中的 ID 不正确,因为我不知道 Peter|John 和 Peter1|John1 如何将他们的 ID 更改为 2。

const master = [
{id:1, value:'John'},
{id:2, value:'Bobby'}
];
const names = [
{id:1, name:'Sandra|John', type:'user', username:'sandraJ'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter|John', type:'user', username:'peteJ'},
{id:4, name:'Bobby', type:'user', username:'be_bob'},
{id:4, name:'Peter1|John1', type:'user', username:'be_bob'}
];
// map the valid names for easier access
const valid_names = master.map(({ value }) => value );
// We could map => filter instead if that's clearer.
const invalid_items = names.reduce(( invalid_items, item ) => {
// Get all the diferent names inside the item.
const item_names = item.name.split( '|' );
// Filter out all the valid names
const invalid_names = item_names.filter( name => !valid_names.includes( name ));
// If there are invalid names remaining, create a new object.
// No idea how the "id" property should be transformed.
if ( invalid_names.length ) {
invalid_items.push({
id: item.id,
name: invalid_names.join( '|' )
});
}
return invalid_items;
}, [] );
console.log( invalid_items );

关于javascript - 从javascript中的2个数组对象中获取不匹配的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52003329/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com