Reputation: 67
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.
Upvotes: 0
Views: 58
Reputation: 597
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.
Upvotes: 0
Reputation: 242
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>
Upvotes: 1
Reputation: 103
Array.find might be what you need:
> arr.find(e => e.Id === 2)
{ Id: 2, name: 'Test2' }
Upvotes: 1
Reputation: 31
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)});
Upvotes: 0
Reputation: 484
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
Upvotes: 0