[英]Get uniq nested object array with lodash
我的數據具有數組嵌套的對象。 我想使嵌套對象的屬性從輸出中變得唯一。 當前,我在上面使用lodash v4,我找到了合適的解決方案,但僅在lodash v3中有效。
數據
[{
menu: { id: 1 },
other: { data: "another1" }
},
{
menu: { id: 2 },
other: { data: "another2" }
},
{
menu: { id: 1 },
other: { data: "another1" }
}]
預期產量
[{
menu: { id: 1 },
other: { data: "another1" }
},
{
menu: { id: 2 },
other: { data: "another2" }
}]
類似的lodash v3解決方案在這里 。 v4的解決方案是什么? 只要代碼運行得更快,更簡單,沒有lodash的解決方案仍然可以接受。
您可以使用uniq
方法,如下所示。
var arr = [{ menu: { id: 1 } }, { menu: { id: 2 } }, { menu: { id: 1 } }]; var unique = _.uniq(arr, 'menu.id'); console.log(unique);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
對於lodash 4.xx,請使用uniqBy
var arr = [{ menu: { id: 1 }, other: { data: "another1" } }, { menu: { id: 2 }, other: { data: "another2" } }, { menu: { id: 1 }, other: { data: "another1" } }]; console.log(_.uniqBy(arr, 'menu.id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
沒有lodash
使用Array#reduce
var a =[{ menu: { id: 1 }, other: { data: "another1" } }, { menu: { id: 2 }, other: { data: "another2" } }, { menu: { id: 1 }, other: { data: "another1" } }] var res =[]; var fin =a.reduce((a,b)=> { if(!res.includes(b.menu.id)){ res.push(b.menu.id) a.push(b) } return a; },[]) console.log(fin)
也許
_.uniqBy(yourarray, e=>e.menu.id)
var data = [{ menu: { id: 1 }, other: { data: "another1" } }, { menu: { id: 2 }, other: { data: "another2" } }, { menu: { id: 1 }, other: { data: "another1" } }] console.log(_.uniqBy(data, e=>e.menu.id));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.