【问题标题】:facing Problem in finding id for name in Json value面临在 Json 值中为名称查找 id 的问题
【发布时间】:2019-06-09 05:40:31
【问题描述】:

我正在处理 Angular 项目,我在存储名称的 id 时遇到问题 在变量中

例子:

[
{ttypeName: Cricket , ttypeUid: 1}
 {ttypeName: Hockey, ttypeUid: 2} , 
{ttypeName: nba, ttypeUid: 3}  , 
{ttypeName: football, ttypeUid:4}  , 
{ttypeName: kabadi, ttypeUid: 5}  ]

我们有 name ,现在我们要匹配 MatchId 并将其存储在变量中并使用它

注意:JASON 值不是静态的,长度和顺序也不是固定的,值来自服务

我在下面发布我的代码 ->

说明我在包含 ttypeName 的函数中传递 sportstype 我想得到它的 ttypeUid p>

为此我编写代码:

this.responsesportstypedata.find(m => m.ttypeName == sportstype ).ttypeUid;

输出: 但这是返回错误的 id , 例如,它返回 ttypeUid : 3 for ttypeName: Cricket ;

getmatchDetails(sportstype) {

           this.rest.getSportstype().then(
                 result => {
                  this.responsesportstypedata = result;


                  this.sportsUid =   this.responsesportstypedata.find(m => m.ttypeName == sportstype ).ttypeUid;


                },
                   err => {
                  this.router.navigate(['ErrorPage']);
                     }
                  );

【问题讨论】:

  • 请发布一些代码,说明您到目前为止尝试了什么,或者您遇到了什么问题。
  • @SachinGupta 我已经修改了我的代码并发布了我的代码,请检查

标签: angular ionic-framework angular5 angular6 angular-services


【解决方案1】:

这里需要的是array.find()

let matchElement = results.find(t=>matchId == yourId);

【讨论】:

  • 我尝试按照您建议的方式工作,但没有成功,我添加了更多代码并解释了更多内容,请您检查
【解决方案2】:

应该是我理解的问题

const nameToFindBy = '...';
const matchId = this.matches.find(m => m.name === nameToFindBy).MatchId;

【讨论】:

  • 我尝试按照您建议的方式工作,但没有成功,我添加了更多代码并解释了更多内容,请您检查
  • @TestingAnurag 你确定this.responsesportstypedata 返回一个数组吗?任何输出到控制台?可以逐行调试吗?
  • 是的,返回数组 (4) [{...}, {...}, {...}, {...}]
  • 你在分配后尝试console.log(this.sportsUid)吗?任何控制台错误等?
猜你喜欢
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多