0

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>
1
  • 2
    No, you would require some looping Commented Dec 8, 2014 at 11:58

2 Answers 2

2

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.

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

Comments

1

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.

1 Comment

How can I use this in the View?

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.