Reputation: 1302
I have a json data like this
[{
"ID":699,
"key":"directorname",
"value":"SampleValue"}
,{
"ID":700,
"key":"template_post_type",
"value":"Sample2ndValue"}]
Now for example I want to retrieve value by "directorname" key.
Is it possible to retrieve value in AngularJS without using repeat syntax?
Note: I want to show value in view (html).
data {"fields": ["directorname", "template_post_type"]}
view structure:
<div ng-repeat="thekey in data.fields">
<span>here for value</span>
</div>
Upvotes: 0
Views: 8643
Reputation: 216
You can use angular.fromJson
and Array.prototype.filter
methods:
var a = '[{"ID":699,"key":"directorname","value":"SampleValue"},{"ID":700,"key":"template_post_type","value":"Sample2ndValue"}]';
var objArr = angular.fromJson(a).filter(function(item) {
if (item.key === "directorname") {
return true;
}
});
console.log(objArr[0].value);
This variant can find all values satisfied condition key === "directorname"
.
Here is jsfiddle example.
Upvotes: 1
Reputation: 106375
Assuming arr
variable has the data, there's one way to get the value:
var val, i = arr.length;
while (i--) {
if (arr[i].key === 'directorname') {
val = arr[i].value;
break;
}
}
Purely angular-ish way, I suppose, would be extracting the required element from arr
with $filter:
var val = $filter('filter')(arr, {key: 'directorname'}, true)[0].value;
... but that's, I suppose, too much for such a simple operation.
Upvotes: 2