Querying Typescript array collection based on key

人盡茶涼 提交于 2019-12-14 04:28:06

问题


I am new to Typescript. I have an Array of type in typescript.Basically containing the collection elements as

"ID": "669a8156-528c-43ba-8ed0-d07874534d1c",
"Name": "Temple",
"DeviceCount": "0",
"SiteCount": "0"

"ID": "5965ee85-2300-4c95-8743-b626f744082f",
"Name": "Building",
"DeviceCount": "2",
"SiteCount": "3"

..so on

How do I query the Name property from the collection if I have the ID

i.e., something similar to LINQ type of expression

var result = array.Where(item => item.ID == ID);

回答1:


You can use the JavaScript Array#filter method for this, which returns an array of matches, very similar to your LINQ code:

array.filter(item => item.ID === ID)[0].name;

You could also use Array#find, but that doesn't have very good browser support, so you might need a polyfill for Opera and Internet Explorer:

array.find(item => item.ID === ID).name;

Read documentation about it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter



来源:https://stackoverflow.com/questions/37982220/querying-typescript-array-collection-based-on-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!