如何通过匹配其ID查找对象属性名称

时间:2020-03-11 04:31:49

标签: html angular typescript

我有一个简单的json数据,我需要通过比较对象的ID来获取对象的名称。假设我有一个数字2,我需要与对象的ID进行比较,如果它等于2,那么我需要获取匹配项对象的对象属性“名称”。就像这里,它将与我的json中的名称“狗”匹配。这是下面的代码 https://stackblitz.com/edit/angular-dtyvrc?file=src%2Fapp%2Fapp.component.ts

app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  ngOnInit() {
  let statusdata1 = [{"id":1,"name":"cat"},{"id":2,"name":"dog"}]
  console.log('dog')
  }
}

6 个答案:

答案 0 :(得分:0)

使用数组查找

let statusdata1 = [{"id":1,"name":"cat"},{"id":2,"name":"dog"}] 

let foo = statusdata1.find(x => x.id === matchingId)

console.log(foo)

答案 1 :(得分:0)

objName: any = "";// declare it as a global variable
id=2;
statusdata1.forEach((obj)=>{if(obj["id"]==id)objName=obj["name"]});
console.log(objName);

答案 2 :(得分:0)

statusdata1.find(x => x.id === 2)?.name;

答案 3 :(得分:0)

您可以通过这种方式获取输出。

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  ngOnInit() {
    let statusdata1 = [{ id: 1, name: "cat" }, { id: 2, name: "dog" }];
    console.log("dog");
    let value = this.getName(statusdata1, 2)
    alert(value);
  }
  getName(dataList, id) {
    let data = dataList.find(a => a.id == 2);
    if (!!data) {
      return data.name;
    }
  }
}

答案 4 :(得分:0)

尝试这样

 const data = statusdata1.find(x => x.id === 2)?.name;

答案 5 :(得分:0)

以下是要添加到app.component.ts中的代码

  result: any; // variable to hold name for mathched id
  idToCompare = 2; // id to comapre from array 

  ngOnInit() {
   let statusdata1 = [{"id":1,"name":"cat"},{"id":2,"name":"dog"}]

   this.result = statusdata1.find(x => x.id === this.idToCompare).name;
   console.log(this.result); // result will be dog
 }

app.component.html

<p>Name of compared id found result:-><b> {{result}}</b> </p>

以下是工作示例的更新URL How to find object property name by matching its id

希望这会有所帮助。