Posted in Javascript onJune 04, 2019
本文实例讲述了JS数组中对象去重操作。分享给大家供大家参考,具体如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>3water.com js数组中对象去重</title> </head> <body> <script> var tmp = [ { "id": 1, "magicId": "111111111111111111", "username": "longzhoufeng", }, { "id": 2, "magicId": "333333333333333333", "username": "longzhoufeng", }, { "id": 3, "magicId": "555555555555555555", "username": "longzhoufeng", }, { "id": 4, "magicId": "666666666666666666", "username": "longzhoufeng", } ] var result = []; var full = {}; for(var i = 0; i < tmp.length; i++) { var aaa = tmp[i].magicId; var bbb = tmp[i].id; if(!full[aaa]) { if(!full[bbb]) { var obj = {} obj.id = tmp[i].id; obj.magicId = tmp[i].magicId; result.push(obj) full[bbb] = true; } full[aaa] = true; } } console.log(full) console.log(result) </script> </body> </html>
运行结果:
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.3water.com/code/HtmlJsRun测试上述代码运行效果。
JS数组中对象去重操作示例
- Author -
longzhoufeng声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@