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);
Related
I would like to know if it's possible to get the name of the objet1 & objet2 without specifying 'objet1' & 'objet2'?
let tableauObj = [
objet1: {name: Albert},
objet2: {name: Florence}]
You can refer to objects in an array by their index within the array. Click these links to learn more about objects and arrays in JavaScript.
let tableauObj = [
{name: "Albert"},
{name: "Florence"}];
// The object with the name property of "Albert"
// is at index zero of the tableauObj array:
console.log(tableauObj[0].name);
// The object with the name property of "Florence"
// is at index one of the tableauObj array:
console.log(tableauObj[1].name);
I am following a tutorial on Youtube about importing data into existing todo list component in React.
If you look at the code below, at the const data object, there are two keys namely lists and listIds. There are two parts which I don't understand.
Why is the key "list-1" a string while the value {id: "list-1",title: "Todo",cards,}
is a normal object? I could not figure out this syntax. If it's JSON format, both key-value should be a in quotation marks.
Is the listIds: ["list-1"] just a normal key-value pair which has an array as its value? If so, why does it has the same name as the one from the initial lists keys? Is this a Destructuring method from ES6?. I just cannot understand the syntax.
const cards = [
{
id: "card-1",
title: "Learning how to cook",
},
{
id: "card-2",
title: "Making sandwich",
},
{
id: "card-3",
title: "Taking the trash out",
},
];
const data = {
lists: {
"list-1": {
id: "list-1",
title: "Todo",
cards,
},
},
listIds: ["list-1"],
};
export default data;
Because "list-1" contains a minus sign and that would be an error for an identifier name. It would be like trying to subtract 1 from "list" and use the expression as a key.
listIds : ["list-1"] is a normal JS key-value expression with a key to the left of : and an array with a single string value to the right.
Object data.lists looks like it contains various sub-objects, each having an ID and listIds is just an array containing all the keys in lists. In your example there is one sub-object and correspondingly, one key in listIds.
One more thing: In a JSON string, keys to the left of : must be in double quotes, however this is a Javascript object, and Javascript objects can have keys without double quotes as long as each key is formatted as a regular Javascript variable, as well as values to the right of : that many times cannot be represented in a JSON string, such as functions for example.
I just thought I'd add a little summary here about declaring key/value pairs in an object declaration. When you declare an object property as in:
let obj = {prop: value};
the left hand side of the property declaration is the property name. There are three possible syntaxes allowed for that:
Plain String - No Quotes
// no quotes - this is allowed when the property name
// doesn't contain any reserved characters
let obj = {prop: value};
Quoted String
// quotes - this is always allowed, but is required when the property name
// does contain reserved characters like a "-" such as your example of "list-1"
let obj = {"prop": value};
Brackets around a variable name
// computed property name. This is used when the property name you want to use
// is in a variable
let someVar = "prop";
let obj = {[someVar]: value};
All three of these options above create the exact same key/value pair in that object.
The right hand side of the prop: value pair can be any Javascript expression like these:
let obj = {prop: 3}; // a number
let obj = {prop: "foo"}; // a string
let obj = {prop: value}; // value from some variable
let obj = {prop: [1,2,3]}; // an array
let obj = {prop: resultFromCallingFunc()}; // the result from calling some function
let obj = {prop: {greeting: "hello"}}; // another object
let obj = {prop: 3 + 4}; // any expression
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.
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]
}
I'm looking for an easy and efficient way to pigeon-hole business objects to be recalled later by ID in some sort of dictionary. I have this method working but it appears it may be unnecessarily using a lot of memory.
var objects = [{ ID: 20, Description: 'Item 1'},
{ ID: 40, Description: 'Item 2'},
{ ID: 60, Description: 'Item 3'}];
var objectsByID = [];
$.each(objects, function (index, o) {
objectsByID[o.ID] = o;
});
var itemID40 = objectsByID[40];
Firebug tells me that objectsByID has undefined array elements in-between the ID numbers that have been added, like so:
[undefined, ... ,
Object { ID=20, Description="Item 1"}, ... ,
Object { ID=40, Description="Item 2"}, ... ,
Object { ID=60, Description="Item 3"}]
Are these array indexes actually assigned and using memory, or is this a conceptual view?
Also, should I be doing this?
JavaScript arrays are sparse, so no, you're aren't taking up extra memory like that. The downside though, and the reason why consoles display it like that, is that the length property will be equal to your highest index + 1.
Some explanation:
All array indices are converted into strings and treated exactly the same as object properties. You can do the following test in the console:
var a = [];
a[100] = "hello";
a["100"]; // "hello"
a.hasOwnProperty("100"); // true
a.hasOwnProperty("0"); // false
To show that this isn't the same as a property that's declared but 'undefined':
a[0] = undefined;
a.hasOwnProperty("0"); // true
var objects = {
"20": { ID: 20, Description: "Item 1" }
"40": { ID: 40, Description: "Item 2" }
}
Don't use an array. Use an object and duplicate the key. You can still treat it as an array but with an array it will create spaces 1-19 here you just have two keys which happen to be called "20" and "40".
Of course you can just use arrays anyway because it doesn't really matter that much in terms of memory usage with a bunch of undefined objects. We don't allocate blocks of memory equivelant to the largest block in the array like we do in C.