how to find the props in obj with variable name in javascript - javascript

I am passing my string to the below function.
$scope.sort= function(query){
console.log(query); // results "name";
$scope.resultset.sort(function(a, b) {
return parseFloat(b.query) - parseFloat(a.query); //results undefined;
});
};
where b and a are my objects in resultset Array.
How to find the props in obj with variable name?

I suppose you mean accessing an object property with a dynamic name.
In javascript, you can access any object propert with an array-like notation:
b.query
is equivalent to :
b["query"]
So you could do :
var property = "query";
var value = b[property];

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

AngularJS $scope variable into one bind to display in html [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' }

How to fetch a value from JavaScript array?

I have a JavaScript array and I want to get the value of last name from it.
Can anyone tell how to get that from this array example:
var result = [{"FirstName":"paapu","LastName":"gandhi"}];
You have an array containing an object, so you have to retrieve the object by doing:
var myObj = result[0]
And then get the LastName property by:
var lastname = myObj.LastName
Get the first object.
var obj = result[0];
Refer to the property of the object:
var prop = result[0].FirstName;
If property name comes dynamically, that is, from a variable, use square bracket notation.
var myVar = "FirstName";
var prop = result[0][myVar];

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

Javascript function push problem

i've following JS function.
responseData:function(resp){
this.jsondata = eval('(' + resp + ')');
this.propList = [];
for (var i = 0;i<this.jsondata.length;i++) {
for (obj in this.jsondata[i]) {
alert(obj); //shows the property name of obj
this.propList.push({
obj : this.jsondata[i][obj] //insert only simple obj string
});
}
}
return this.propList;
}
I want to insert in my propList the property name and the value, but instead inserting the property name this function inserts simple 'obj' as a string. What i'm doing wrong?
greetings
Stefan
Change the loop to,
for (obj in this.jsondata[i]) {
alert(obj); //shows the property name of obj
var item = {};
item[obj] = this.jsondata[i][obj];
this.propList.push(item);
}
When you use object-literal to create an object the property names are not evaluated as variables. To specify the name of an objects property using a variables current value, you must use the obj[variable] format. This will create a property within obj whose name will be the same as current value of variable.

Categories