简体   繁体   English

过滤 Object 和 Typescript 中的返回键

[英]Filter an Object and Return Key in Typescript

I have an object to be filtered and it should return a key that has a specific id.我有一个要过滤的 object,它应该返回一个具有特定 ID 的密钥。 Id is Unique. ID 是唯一的。 Need an efficient logic to return this expected output.The Object to be filtered.需要一个有效的逻辑来返回这个预期的 output。要过滤的 Object。

{
  "a":[{"id":"1123","value":"test1"}],
  "b":[{"id":"1124","value":"test2"}],
  "c":[{"id":"1125","value":"test3"}]
  
}

Input Id : "1124"输入 ID :“1124”

Expected Output  : 'b'

 let data = { "a":[{"id":"1123","value":"test1"}], "b":[{"id":"1124","value":"test2"}], "c":[{"id":"1125","value":"test3"}] }; let input = "1124"; let result = Object.entries(data).filter(([k,v]) => v[0].id === input)[0][0]; console.log(result);

Efficiencies here:这里的效率:

  • break the loop as soon as something is found一旦发现东西就打破循环
  • not interested in the object that has the id, only in checking that something there has that id对有 id 的 object 不感兴趣,只检查那里有那个 id

 o = { "a":[{"id":"1123","value":"test1"}], "b":[{"id":"1124","value":"test2"}], "c":[{"id":"1125","value":"test3"}] } for (key in o) { if (o[key].some(x => x.id === '1124')) { console.log(key); break; } }

 const input = "1124" const obj = { "a":[{"id":"1123","value":"test1"}], "b":[{"id":"1124","value":"test2"}], "c":[{"id":"1125","value":"test3"}] } Object.values(obj).filter((ob, i)=>{if(ob[0].id === input){console.log(Object.keys(obj)[i])}})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM