3

I have the following code:

Person = new Backbone.Model({
 data:[
    { age: "27" },
    {name: "alamin"}
]
});

now, how can I get the value?

person=new Person();
person.get(?);

Please provide me with a solution.

2
  • Models are supposed to contain scalar data Commented Jul 17, 2012 at 11:46
  • I'm pretty sure you should be using Backbone.Model.extend and maybe you mean defaults rather than data, as you have given it initial values. Commented Jul 17, 2012 at 11:54

4 Answers 4

3

If you're using this model:

Person = new Backbone.Model({

data:[
    { age: "27" },
    {name: "alamin"}
]

});

So if you want to pull from an array within a model explicitly you should try this:

i = new App.Model.Person();
i.fetch();
i.get("data")[0].age;

This would return:

27

From there you can iterate through the data however you prefer.

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

2 Comments

How is this answer providing a solution that is different from the other answers that were given years earlier?
This really helped me with SAPUi5, tho its getProperty("data") there.
1

I don't know of a data property when defining a model - maybe you mean defaults? as in

var Person = Backbone.Model.extend({
   defaults: {
      property1: value1,
      property2: value2,
      property3: ["arrval1", "arrval2", "arrval3"]
   });

You would retrieve the value of certain property using get: myperson.get('property1'). To set the value of a property use set: myperson.set('property1', 'newValueOfProperty')

If a property is an array the myperson.get('property3')[ index ]

Comments

0

To get the array as an object:

Use person.get('data')

To get the value of an attribute from the array:

Use person.get('data').name

Or person.get('data')['name']

Comments

0

To obtain attributes of a specific element of the array:

var people = person.get('data'); // This gets the array of people.
var individual = people[0];      // This gets the 0th element of the array.
var age = individual.age;        // This gets the age property.
var name = individual.name;      // This gets the name property.

Comments

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.