AngularJS $scope variable into one bind to display in html [duplicate] - javascript

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?

There's the dot notation and the bracket notation
myObj[a] = b;

ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};

Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")

Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.

Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?

You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.

You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'

As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.

The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }

Related

What does the es6 { [a]: b } destructuring mean?

There is some destructuring going on here:
const { [a]: b } = this.props
But, what does [a]: b do: what does the brackets with colon do?
In my case, a is supplied as one of the props with a string value.
This ES6 destructuring syntax is very similar to the new "Enhanced object literals" for defining objects with variable property names, so I think it's useful to see that first:
Pre-ES6, if you wanted to assign a value to an object with a property name that was variable, you would need to write
var obj = {};
obj[variable] = value
That's because while both the dot-notation and the object literal notation require using the actual property name, the obj[prop] notation allowed you to have a variable name.
ES6 introduced the extended object literal syntax, which included the ability to write
var obj = { [variable]: value }
The same syntax was incorporated in destructuring, which is what your question shows.
The basic destructuring allows assigning variables given literal property names:
First, assigning to a variable with the same name as a property already in the object (docs):
var person = {name: "Mary"};
var {name} = person;
/// name = "Mary"
Second, assigning a variable with a different name than the one already in the object (docs):
var person = {name: "Mary"};
var {name: myName} = person;
/// myName = "Mary"
(Side-note: if you recognize that, in the first example, var {name} = ... was just short-hand for var {name: name} = ..., you'll see that these two examples match more logically.)
But what if you don't know which property you want from person? Then you can use that same new computed-property-name object syntax from above (docs):
var person = {name: "Mary"};
var propName = getPropUserWantToKnowAbout(); // they type in "name"
var {[propName]: value} = person;
/// value = "Mary"
[a] is a computed property name
...allows you to put an expression in brackets [], that will be
computed and used as the property name
{ [a]: b } is a destructuring assignment with assigning to new variable names using a computed property name
A property can be unpacked from an object and assigned to a variable
with a different name than the object property
Thus you end up with having a variable b in current scope that holds the value of this.props[a]
Example
this.props = {foo : 1, bar: 2};
let p1 = 'foo';
let p2 = 'bar';
let { [p1]: b } = this.props;
console.log(b); // 1
let { [p2]: c } = this.props;
console.log(c); // 2
An example
var props = {'dynamic': 2}
var dyn = 'dynamic'
const {[dyn]:a} = props
console.log(a);
// logs 2
Check out this page: https://gist.github.com/mikaelbr/9900818
In short, if dyn is a string, and props has a property with that string as the name, accessible by props[dyn], then {[dyn]:a} = props will assign props[dyn] to a

Reference JS object through concatenation

I am trying to call an object.
The way I am currently doing it:
var key = object_0
The way I'd like to do it
var key = "object_" + questionId;
But when calling the concatenated object_0 I do not get the object info
when I do a:
console.log(key)
Any insight would be awesome.
Short answer: global scope + brackets.
window['object_'+questionId] = 'foo';
console.log(window['object_'+questionId]); // 'foo'
Long answer: Use dynamic variable names in JavaScript
If you use ES5 you can do so with creating new empty object. Here are the steps:
1.create empty object
var o = {};
2. use brackets to produce the new key on an object - ("object_" + questionId) - this will force the parser first to evaluate expression in the brackets
3.assign value to a newly added key
o[("object_" + questionId)] = XXX;
Then console.log(o) will output {object_0: XXX}
You can use the window object (access to global variables only):
var object_0 = { p: 42 },
questionId = 0,
key = "object_" + questionId;
document.write(window[key].p);
But i suggest to change the data structure to a more concise style:
var questions = { 200: { p: 42 }},
questionId = 200;
document.write(questions[questionId].p);

Difference between javascript object literal notation and adding to objects

Can someone explain what is happening in the code below? I'd expect toString to get called for either both foo and bar, or neither. How is literal object notation different from adding fields to an object after it is created?
function Obj(v) {
this.v = v;
};
Obj.prototype.toString= function() {
window.alert("to string called for " +
this.v);
return this.v.toString();
}
var foo = new Obj('foo');
var bar = new Obj('bar');
// toString is not called here.
var map = {foo : 'blah'};
// toString is called here.
map[bar] = "blah2";
Why do object literals not use toString() while adding to an existing object does use toString()?
http://jsfiddle.net/pByGJ/2/
The main reason that object literals don't evaluate the identifier to the left of the colon is so you're not force to quote all literal names (as you do in JSON).
Bracket notation forces you to quote property names, if you don't, it will be evaluated as a variable.
The reason toString() does get called in the second example is because bar has to be converted to a string to be used as a property name.
In your first example, you're just creating a literal object (that is the exactly the same as {"foo" : 'blah'}). So that is never using the variable foo
If you want to create an object using a variable name, you can't use literal object notation, you have to use [] which is what forces it to call toString()
Here's a function to create objects with variable names in one expression.
function obj(key, value /*, key, value, ... */) {
var obj = {};
for (var i = 0, ln = arguments.length ; i < ln; i+=2) {
obj[arguments[i]] = arguments[i+1];
}
return obj;
}
Clearer Example
The fact that your variable names and values are the same doesn't help understanding the problem. Let me suggest this code
var foo = new Obj('fooValue');
var bar = new Obj('barValue');
var map = {foo : 'blah'};
map[bar] = "blah2";
// You expect map to be {fooValue: 'blah', barValue: 'blah2'}
// But it's {foo: 'blah', barValue: 'blah2'}
To do what you need, use my obj function
// Almost as clear as literal notation ???
var map = obj(
foo, 'blah',
bar, 'blah2'
);
// map = {fooValue: 'blah', barValue: 'blah2'} Yay!!
keys in an object literal are taken as strings, not interpreted as variables. This:
var map = {foo : 'blah'};
is equivalent to this:
var map = {"foo" : 'blah'};
and this:
var map = {};
map["foo"] = "blah";
but is completely different than this:
var map = {};
map[foo] = "blah";

How to set a Javascript object values dynamically?

It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});

How to create an object property from a variable value in JavaScript? [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 7 years ago.
I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:
var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;
alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'
In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?
There's the dot notation and the bracket notation
myObj[a] = b;
ES6 introduces computed property names, which allow you to do
var myObj = {[a]: b};
Dot notation and the properties are equivalent. So you would accomplish like so:
// const myObj = new Object();
const myObj = {};
const a = 'string1';
myObj[a] = 'whatever';
alert(myObj.string1);
(alerts "whatever")
Ecu, if you do myObj.a, then it looks for the property named a of myObj.
If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.
Oneliner:
obj = (function(attr, val){ var a = {}; a[attr]=val; return a; })('hash', 5);
Or:
attr = 'hash';
val = 5;
var obj = (obj={}, obj[attr]=val, obj);
Anything shorter?
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
As $scope is an object, you can try with JavaScript by:
$scope['something'] = 'hey'
It is equal to:
$scope.something = 'hey'
I created a fiddle to test.
The following demonstrates an alternative approach for returning a key pair object using the form of (a, b). The first example uses the string 'key' as the property name, and 'val' as the value.
Example #1:
(function(o,a,b){return o[a]=b,o})({},'key','val');
Example: #2:
var obj = { foo: 'bar' };
(function(o,a,b){return o[a]=b,o})(obj,'key','val');
As shown in the second example, this can modify existing objects, too (if property is already defined in the object, value will be overwritten).
Result #1: { key: 'val' }
Result #2: { foo: 'bar', key: 'val' }

Categories