无法根据另一个对象数组过滤对象数组
Posted
技术标签:
【中文标题】无法根据另一个对象数组过滤对象数组【英文标题】:Unable to filter an array of object based on another array of object 【发布时间】:2021-10-24 00:54:29 【问题描述】:我有两个对象数组,其中包含 dateTime
字符串和 count
的键值对。在arr
中,我有两个对象具有相同的dateTime
值和brr's
对象的dateTime
值中的两个。我只想过滤掉数组中的arr's
不相等的对象。
我的意思是,如果我的arr
是这样的:
const arr = [
dateTime: '2021-08-14 02:00:00', count: 1 ,
dateTime: '2021-08-15 04:00:00', count: 1 ,
dateTime: '2021-08-16 10:00:00', count: 1 ,
dateTime: '2021-08-16 19:00:00', count: 1 ,
dateTime: '2021-08-17 05:00:00', count: 1
];
brr
是这样的:
const brr = [
dateTime: '2021-08-16 19:00:00', count: 1 ,
dateTime: '2021-08-17 05:00:00', count: 1
];
我正在尝试获取这样的数组:
[
dateTime: '2021-08-14 02:00:00', count: 1 ,
dateTime: '2021-08-15 04:00:00', count: 1 ,
dateTime: '2021-08-16 10:00:00', count: 1
];
没有这样做:
const arr = [
dateTime: '2021-08-14 02:00:00', count: 1 ,
dateTime: '2021-08-15 04:00:00', count: 1 ,
dateTime: '2021-08-16 10:00:00', count: 1 ,
dateTime: '2021-08-16 19:00:00', count: 1 ,
dateTime: '2021-08-17 05:00:00', count: 1
];
const brr = [
dateTime: '2021-08-16 19:00:00', count: 1 ,
dateTime: '2021-08-17 05:00:00', count: 1
];
const newArr = [];
for( let item of brr )
const filtered = arr.filter( el =>
return el.dateTime !== item.dateTime;
);
newArr.push( filtered );
;
console.log( newArr );
我在控制台中遇到了一些乱码。我在这里做错了什么?
【问题讨论】:
看看这对你有没有帮助***.com/questions/54142112/… 【参考方案1】:试试这个:
const newArr = [];
const brrDateTimes = brr.map((el) => el.dateTime);
arr.forEach((el) =>
if (brrDateTimes.indexOf(el.dateTime) == -1)
newArr.push(el)
);
【讨论】:
【参考方案2】:您可以获取一组不需要的 dateTime
值并过滤数组。
const
array = [ dateTime: '2021-08-14 02:00:00', count: 1 , dateTime: '2021-08-15 04:00:00', count: 1 , dateTime: '2021-08-16 10:00:00', count: 1 , dateTime: '2021-08-16 19:00:00', count: 1 , dateTime: '2021-08-17 05:00:00', count: 1 ],
filter = [ dateTime: '2021-08-16 19:00:00', count: 1 , dateTime: '2021-08-17 05:00:00', count: 1 ],
unwanted = new Set(filter.map(( dateTime ) => dateTime)),
result = array.filter(( dateTime ) => !unwanted.has(dateTime));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
【讨论】:
【参考方案3】:time=brr.map(x=>x.dateTime);
arr.map(x=>!time.includes(x.dateTime))
【讨论】:
【参考方案4】:Array.filter 对整个数组进行操作。您不需要在循环中调用它。此外,在比较对象的相同性时,您需要比较它们的标量值。在 javascript 中,具有相同值的对象仍然不相同。
const arr = [
dateTime: '2021-08-14 02:00:00', count: 1 ,
dateTime: '2021-08-15 04:00:00', count: 1 ,
dateTime: '2021-08-16 10:00:00', count: 1 ,
dateTime: '2021-08-16 19:00:00', count: 1 ,
dateTime: '2021-08-17 05:00:00', count: 1
];
const brr = [
dateTime: '2021-08-16 19:00:00', count: 1 ,
dateTime: '2021-08-17 05:00:00', count: 1
];
const diff = arr.filter(a =>
return !brr.some(b =>
return a.dateTime === b.dateTime && a.count === b.count;
);
);
console.log(diff);
【讨论】:
以上是关于无法根据另一个对象数组过滤对象数组的主要内容,如果未能解决你的问题,请参考以下文章