从对象数组中删除重复项JavaScript
我们需要编写一个函数,该函数从数组中删除重复的对象并返回一个新的对象。如果一个对象具有相同数量的键,相同的键和每个键的值,则将它们视为另一对象的副本。
让我们为此编写代码-
我们将使用映射以字符串形式存储不同的对象,一旦看到重复的键,我们将忽略它,否则我们将对象推入新数组-
示例
const arr = [
{
"timestamp": 564328370007,
"message": "It will rain today"
},
{
"timestamp": 164328302520,
"message": "will it rain today"
},
{
"timestamp": 564328370007,
"message": "It will rain today"
},
{
"timestamp": 564328370007,
"message": "It will rain today"
}
];
const map = {};
const newArray = [];
arr.forEach(el => {
if(!map[JSON.stringify(el)]){
map[JSON.stringify(el)] = true;
newArray.push(el);
}
});
console.log(newArray);输出结果
控制台中的输出将为-
[
{ timestamp: 564328370007, message: 'It will rain today' },
{ timestamp: 164328302520, message: 'will it rain today' }
]热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿