0

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. enter image description here

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.

7
  • var search=36;for(var i=0;i<array.length();i++){if(array[i].id=search){console.log("Here I am!");break;}} Commented Apr 28, 2017 at 10:22
  • Hi Simon, the problem is that I can not do the array.length. I just can do it if I do array[0].length() Commented Apr 28, 2017 at 10:24
  • Instead of using Array.prototype.filter and plucking the first element you can also use Array.prototype.find which will do that for you. Commented Apr 28, 2017 at 10:24
  • How come you can't use array.length? If it's an array of objects it should work (as in if it doesn't something is seriously wrong)... I'm assuming you have something like var array = [{id:36},{id:35}]; Commented Apr 28, 2017 at 10:28
  • length is not a function, so for array # of items use .length Commented Apr 28, 2017 at 10:29

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.