0

I have a resource in AngularJS returning an object that looks something like this:

[
 {
  field: {
   name: 'foo'
  },
  field_value: 'bar'
 },
 {
  field: {
   name: 'foo2'
  },
  field_value: 'bar2'
 } 
]

Each field name will be unique, and I want to be able to pull out values by name to populate a form. Something like this:

<input type="text" value="{{data.foo}}" />  # this should equal 'bar'

How can I filter that object to easily access the values? Or should I perform a transformation on the data first?

2 Answers 2

1

Yes, transforming the data into a proper form is best. I recommend performing the data manipulation in the resource that returns it, before the return.

var newData = {};

data.forEach(function (item) {
        newData[item.field.name] = item.field_value;
    }
);

console.log(newData.foo);
Sign up to request clarification or add additional context in comments.

Comments

0

Transform the data info a form, which serves your GUI. You'll avoid a lot of troubles.

3 Comments

Sorry, I'm a newb. Do you mean that I should do a transformResponse as it's coming out of the service rather than trying to build my form around the wonky response?
No obviously your JSON structure doesn't serve your GUI very well. Best is to put in another form.
That doesn't really help me. I don't have control over the JSON response.

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.