0

I have a JSON array as follows

[{"Id": 1,"name":"Test1"}, 
 {"Id": 2,"name":"Test2"},
{"Id": 3,"name":"Test2"}]

And I want to get the name of the Id which equals to 2(Id=2) through angularJS. I am a newbie to angularjs.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Madhavee
  • 67
  • 8

5 Answers5

1

Array.find might be what you need:

> arr.find(e => e.Id === 2)

{ Id: 2, name: 'Test2' }
Dominic Porter
  • 103
  • 1
  • 8
1

Try the below code:

var jsonArray = [{"Id": 1,"name":"Test1"}, 
 {"Id": 2,"name":"Test2"},
{"Id": 3,"name":"Test2"}];


var name = Object.keys(jsonArray).find(e => {
if(jsonArray[e].Id == 2)
{
   console.log(jsonArray[e].name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Bijay Koirala
  • 242
  • 2
  • 10
0

Not the prettiest but this works

function findObjectByKey(array, key, value) {
    console.log(array);
    for (let i = 0; i < array.length; i++) {
        console.log("looking for:", i);
        if (array[i] !== undefined && array[i][key] === value) {
            console.log("found at:", i);
            return i;
        }
    }
    return null;
}

array is the array you want to search key would be 'id' in your case and value woulde be 2 or whatever you are looking for

it returns the index of the object in the array but can easily be modified to return the name like this:

if (array[i] !== undefined && array[i][key] === value) {
            console.log("found at:", i);
            return array[i]['name'];
        }

I know there is a more efficient way probably but this is what i first thought of

lwolf
  • 475
  • 3
  • 12
0

Assuming that you have this array:

var arr = [{"Id": 1,"name":"Test1"}, 
           {"Id": 2,"name":"Test2"},
           {"Id": 3,"name":"Test2"}];

You can always use a forEach through your array:

arr.forEach((a) => {if(a.Id == 2) console.log(a.name)});
cortereal
  • 31
  • 4
  • I tried your method. But I get the following Error. "TypeError: arr.forEach is not a function" @cortereal – Madhavee Apr 10 '19 at 08:33
0

Try below code,

let userArr = [{"Id": 1,"name":"Test1"}, 
              {"Id": 2,"name":"Test2"},
              {"Id": 3,"name":"Test2"}];

let userId = 2;

let item = userArr.find(e => {
     return e.Id === userId;
});

console.log(item); 

You can use also Filter JS Filter.

Manoj Ghediya
  • 547
  • 1
  • 7
  • 19