简体   繁体   中英

How to find the name property from an array of Objects

I am trying to get the value from an array of objects given the id, but I am not able to make it working. The problem is that I have an array of objects, so I don't know how to iterate over them. I know using the .map method could be a possible solution, but I'm new on this.

my method is that given a Id, it has to return me the name from the same object. 在此处输入图片说明

How could I iterate over them? I am using this actually:

getName(field_id: any): any {
var aux = 0;

  var obj = this.customFields[aux].filter(function (obj) {
    return obj.name === field_id;       
  })[0];
  aux ++;
}

where aux is an iterator. Ofc is not working.

considering array containing the objects, you can just use the filter function, no neeed to use the indexer

 var arr = [ {id: 1, name: "something"}, {id: 2, name: "something1"}, {id: 3, name: "something2"}, {id: 4, name: "something3"}, {id: 5, name: "something4"} ] var id=3 var obj = arr.filter(function(obj) { return obj.id === id; }) console.log(obj[0].name) 

I think your issue is that you compare the name with the id. If you want to avoid loops:

// This find the correct entry corresponding to the id you are looking for
var correctField = this.customFields.find(function(field) {
  return field.id === field_id;
});
// Then you get the name from the entry
var nameToFind = correctField && correctField.name;

You might have to replace find depending on your browser support.

A way to replace it: this.customFields.filter()[0]

You can simply use for loop as below

var arr = [{id:1,name:"abc"},{id:2,name:"pqr"},{id:3,name:"lmn"}]

function getName(id){
  for(var i=0;i<arr.length;i++)
    if(arr[i].id==id)
      return arr[i].name;
   return null 
}

getName(2);// pqr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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