猿问

根据 object.differentValue === 静态值仅将 object.value

试图找出最好的方法来做到这一点,而不会碰到坏的 bigO。基本上我有一个值标识符name,我只想object.id根据 if获取对象中的唯一值object.name === name,因此Set()将包含仅与找到名称的条件相关的 id。


例子...


const uniqueIds = new Set();

const name = "billy";

const objects = [

    {id: 1, name: "billy"},

    {id: 2, name: "billy"},

    {id: 3, name: "jack"},

    {id: 4, name: "kevin"},

]

用 [1,2] 实例化 uniqueIds 的最佳方法是什么?


我真的必须使用 afilter()进入一个新数组,然后使用map()to 然后使用uniqueIds.add(id)吗?


或者有没有更好的方法使用类似的快捷方式来做到这一点insert ids into uniqueIds where objects.name === name?


ibeautiful
浏览 80回答 1
1回答

繁星点点滴滴

您可以使用reduceandSet获取唯一 IDconst name = "billy";const objects = [    {id: 1, name: "billy"},    {id: 2, name: "billy"},    {id: 2, name: "billy"},    {id: 3, name: "jack"},    {id: 4, name: "kevin"},]const uniqueIds = objects.reduce((result, obj)=>{  if(obj.name === name) result.add(obj.id)  return result}, new Set())console.log(Array.from(new Set(uniqueIds)))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答