how to get array element from model in backbone.js - javascript

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.

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.

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 ]

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']

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.

Related

how can I add this object in an array?

How can I add {[]} in an array?
#CertainPerformance is correct. You have to have an associated property if you want to have objects.
var a = [ { propertyName : [] } ]
then you can access that array like this :
a[0].propertyName or a[0]['propertyName']
And you can have multiple values inside the object too :
var a = [
{
propertyName_1 : [],
propertyName_2 : "",
propertyName_3 : 3,
}
];
var a = [{}] // no problem, you are assigning an empty object `{}` as first element of array
var a = [[]] // no problem, you are assigning an empty array `[]` as first element of array
var a = [{[]}] // Not working because you're assigning empty array into object
//object needs key to store value
var a = {[]} //Not ok <<======== have you ever see var a = { 1, 2, 3} ?
Please refer to documentation:
An object is a collection of properties, and a property is an association between a name (or key) and a value.

How to access value from the object within an array?

How can I access Name's value and assign it to an variable?
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
Try this:
var [{Name: name}] = arr;
This uses ES6 destructuring assignment.
First, the outermost [] is a way of referring to an array on the right hand side (in this example, arr). Things placed within these square brackets (here's there's only one) refer to the first, second, and succeeding values of that array. So here, the {Name: name} portion refers to the first (0th) element of the array. In other words, it is equivalent to
var {Name: name} = arr[0];
The inner {} is a way of referring to objects and picking them apart. {Name: name} says to find the Name property of the object being picked apart. Then the : name part says to rename it to name. Since all this is occurring in the context of a var statement, the result is declare a new variable with the name name and assign the value being picked out to it.
Here's the more detailed sequence:
var // Start a variable declaration
[ // Pick apart an array on the RHS, starting with 1st element
{ // Pick apart an object
Name // Find the property named `Name` in that object
:name // Rename it; this is the variable that will be declared!
} // Done picking apart the object
] // Done picking apart the array
= arr; // Specify the thing to deconstruct
Access the element at index 0 of array using bracket notation, then access property name Name of object using dot or bracket notation
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
var name = arr[0].Name; // alternatively, `arr[0]["Name"]`
var arr = [
{Name: "Jason",
Title: "Student",
Image: "asdf",
Status: "Happy"}
];
var myname = arr[0]['Name'];
console.log(myname);

Get link to nested object by string key

For example, I have an object:
var model = {user:{name: 'Mike', phones:{mobile: '00000'}}};
and a string key:
var string_key = 'user.phones.mobile';
I can parse it to get the array key:
var keys = string_key.split('.');
How can I can get link to object phones from model?
By doing this:
model[keys[0]][keys[1]][keys[2]];
This seems a bit strange though..

How to create object inside object in Javascript

I am trying to create an object - that each parameter inside it is another object:
var divTextPerScreenWidthMap = new Object(
{'360','click'},
{'480','click it'},
{'768','click it right'},
{'1024','you know you want to click it'},
{'1280','click this button which is very long will help you'}
);
This is not working since I am getting an error. how do I need to write it to make it work? Should I change the outer object into an Array and how?
You have syntactical errors.
First of all object literal follows the syntax below:
var literal = {
"Name": "value",
"Array": [],
"NestedObject": {}
};
Name value separator is the colon, not comma.
EDIT
The above code might be rewritten as follows
// declaration via array initializer
var myArray = [
// name : value syntax
{'360': 'click'},
// values separated by comma
{'480': 'click it'},
{'768': 'click it right'},
{'1024': 'you know you want to click it'},
{'1280': 'click this button which is very long will help you'}
]
however at this point you cannot access your objects via i'ts names like this:
var firstObject = myArray[0];
// will throw an error
firstObject.360 = "not click";
You can only use it as follows
firstObject["360"] = "not click";
Hence I suggest you to name the properties according to variable naming rules.
In javascript object is a simple map. It is better to use literal {} instead od new Object();
var myObj = {
prop : {},
prop2 : {}
}
Don't create an Object via its constructor, use the literal syntax {}.
Also, objects have keys and properties. Your objects seem to only have values. Did you mean to use Arrays?
You completely forgot to give keys for your values. If you don't want to use keys, use arrays:
var divFoo = [
[360, "click"],
[480, "click it"] // et cetera
];
This would give you an array of arrays. For instance, divFoo[0][0] == 360
If you want keys, use an object:
var divFoo = {
"360": "click",
"480": "click" // et cetera
}
This gives you simple object. divFoo[360] == "click"
Or you could use an array of objects for more descriptiveness:
var divFoo = [
{time: 360, text: "click"},
{time: 480, text: "click it"} // et cetera
];
In this case, divFoo[1].text == "click it".
Also, a few hints:
Don't use new Object or new Array. They're redundant.
There's no need to quote integers if they're used as values.
It would make sense to represent your collection of objects as an array:
var divTextPerScreenWidthMap = [
{360:'click'},
{480:'click it'},
{768:'click it right'},
{1024:'you know you want to click it'},
{1280:'click this button which is very long will help you'}
];
//You could iterate over your array of objects with a for loop:
var i, value;
for (i=0; i < divTextPerScreenWidthMap.length; i++) {
value = divTextPerScreenWidthMap[i];
console.log(value);
};
//Alternatively, you could represent your data structure as one object:
var divTextPerScreenWidthMap = {
360:'click',
480:'click it',
768:'click it right',
1024:'you know you want to click it',
1280:'click this button which is very long will help you'
};
//So now if you have a screen width, you can quickly get back the corresponding message:
var screenWdith = 360;
alert(divTextPerScreenWidthMap[screenWidth]);
You can also created nested objects like this:
let obj1 = {};
obj1['title'] = 'Vehicles';
let obj2 = {};
obj2['name'] = 'Honda City';
obj1['cars'] = obj2;
console.log(obj1);
Create a method in object, create a new object in that method and return it.
const obj = {
one: "one is just a property",
two: function(){
const newObject = {
three: "now two will return new a new object"
}
return two;
}
}

How to add an element containing fields to an array

Using javascript, how can I add to an array an element which contains fields (pairs of field name and field value)?
The purpose of this is that each element will later be inserted as a row to a DB, using ajax.
Just to make sure - after the array is ready I should be able to access a field this way:
shopsArray[4].shopName
Edit:
It's working with Pointy's answer but I still have a problem:
shopsArray.push( { shopId: 1, shopAddress: $('#newAddress' + j).val() } );
The first value is inserted fine, but the second one has a problem.
If I alert $('#newAddress' + j).val() than I get the correct value which has been inserted in the field in the webpage.
But if I alert shopsArray[lastElementNumber].shopAddress than I get undefined.
Can you see what's the problem here?
Edit 2:
More elaborate code:
// save changes in main shop
shopsArray[0].shopName = $('#mainName').val();
shopsArray[0].shopAddress = $('#mainAddress').val();
// save secondary branches to array
for (var i=1; i<shopsArray.length; i++){
shopsArray[i].shopName = $('#secondaryName' + i).val();
shopsArray[i].shopAddress = $('#secondaryAddress' + i).val();
}
// save new branches to array
for (var j=1; j<=newshopsCounter; j++){
var bName = $('#newName' + j).val();
shopsArray.push({shopId: -1, userId: shopsArray[0].userId, shopName: bName, shopAddress: $('#newAddress' + j).val()});
alert(bName);
alert(shopArray[1].shopName);
alert(shopsArray[1].shopId);
}
The first and third alerts give the correct values. The second one gives undefined.
You mean something like
shopsArray.push({ shopName: "Fred", value: "Ethel" });
?
edit — now that I know that this is the sort of thing you want to do, I'll clarify.
JavaScript has an "object literal" syntax that allows objects to be created directly as values. The syntax involves a list of property names and values, with the names and values separated by a colon and each pair separated by commas. Thus:
var anObject = { someProperty: "the value" };
creates an object with one property and assigns it to the variable "anObject". That's effectively the same as:
var temp = new Object();
temp["someProperty"] = "the value";
var anObject = temp;
The "value" part of a property in an object literal can be any expression, but the property name must be either a string constant or an identifier (and in either case, it's treated like a string constant). Thus, you can create an object with a property whose value comes from calling some function:
var fancyObject = { "temperature": getTemperature() };
Object literal expressions are values, and can be used anywhere you can use an expression, including function call arguments. Therefore, to add an object to an array, it's possible to call the array ".push()" function and use an object literal as the argument, as in the first example:
shopsArray.push({ shopName: "Cheese Shoppe", shopPhone: "111 222 3232" });
You can even include object literals inside another object literal, as the value of a property:
shopsArray.push({
shopName: "Cheese Shoppe",
shopAddress: {
street1: "207 High Street",
street2: "No. 5",
city: "Austin",
state: "TX"
}
});
You would simply create a hash inside an array to achieve that:
var shopsArray = [
{
shopName: 'value1'
}, {
shopName: 'value2'
}
];
If you have an existing array, use push:
shopsArray.push({ shopName: 'value' });
you can do something like this:
var arr = new Array();
arr['field_name'] = 'field_value';
//to access it on ajax
for (var i in arr){
//field_name is in "i"
//field_value is in arr[i]
}

Categories