This question already has answers here:
How do I reference the same Object's properties during its creation? [duplicate]
(5 answers)
Closed 9 years ago.
Can one reference own properties on initialization of object?
I have an object that should be unique and only exist as one so I
have no initializer etc.
Using something like this:
var Myobj = {
property1 : aaa,
property2 : bbb,
property3 : {a: self.property1 }
/* ^-- is this somehow possible without using a function?
Or a better way to solve / structure this. .init()
best option? */
};
>> Fiddle <<
The real object, (in the real code), has an add function that takes options on
what function to use etc. It is sort of a wrapper for "addEventListener" where
the point is to be able to remove listener - which require non anonymous function
reference.
Function to use within Myobj is specified by string, or numeric key in options to
Myobj.add().
Object literals remain undefined until the closing }, so you'd either have to make property3 a function or make the whole object a function.
var Myobj = {
property1 : 'aaa',
property3 : function (){ return { a : this.property1 } }
};
or
var MyObj = function(){
this.property1 = 'aaa',
this.property3 = { a: this.property1 }
}
var MyObjInstance = new MyObj();
This has been asked a lot of times: Access properties while declaring object?
It works if you use a placeholder array:
var prop = new Array();
var Myobj = {
property1 : 'aaa',
property2 : 'bbb',
property3 : {a: prop}
};
prop.push(Myobj.property1);
window.alert(Myobj.property3.a);
http://jsfiddle.net/y2XwC/1/
Related
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' }
This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
const json = {
a: 1,
b: 2,
c: "HI"
}
Is there a way to just pass in {a : 1} to function?
var someReturn = aOnly({a : json.a});
I am not sure if destructuring/constructuring of ES6 solves this problem. I can't seem to find the right syntax after reading several ES6 destructuring example.
EDIT
Nothing is wrong with the code I am just asking if there is a syntax to just extract "a" only from JSON without redundantly doing
{a : json.a }
the implementation of aOnly function is not the focus here
You can use ES6 object destructuring on object passed as parameter to pick specific property.
const json = {
a: 1,
b: 2,
c: "HI"
}
function aOnly({a}) {
return a;
}
var someReturn = aOnly(json);
console.log(someReturn)
Thank you I have figured out the right syntax. The initial mistake I was doing was trying to construct directly using { json.a }, hoping that this will automatically turn into { a : json.a} but the right way is do destruct first and construct later.
var json = {
a : "ASDF",
b : 123,
c : "Test"
};
const {a, b, c} = json; // destructing
var aObject = aOnly({a}); // constructing
var bObject = bOnly({b});
var cObject = cOnly({c});
console.log (aObject);
console.log (bObject);
console.log (cObject);
function aOnly(a) { return a; }
function bOnly(b) { return b; }
function cOnly(c) { return c; }
This question already has answers here:
Iterate over Object Literal Values
(8 answers)
Closed 2 years ago.
I have create one object and that object I need to pass in one method where I need to iterate by using each object. Since my Obj having only values so it its not getting passed. Can any one help me into this.
My Code :
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
Now this MyObj I need to pass in one method:
this.someMethod(id, MyObj);
In someMethod i Have one code like
Ext.Array.forEach(MyObj, function (Value) {})
At this point it is getting failed because MyObj is not an array of object. How to correct it.
It would be very helpful if you'd provide more information.
I am not sure what you want to achieve, but there are several ways to iterate through objects.
If you want to split up your object into multiple single-key objects:
> Object.keys(MyObj).map(key => ({ [key]: MyObj[key] }))
[ { country: 'Aus' }, { Time: 'EST' }, { Val: 'Pecific' } ]
On the other hand, if you have a function that takes an array but you want to pass just this one object:
Ext.Array.forEach([MyObj], Value => ())
(But in this case you are better off just calling the function.)
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
//Without ext
function someMethod(id, MyObj)
{
Object.keys(MyObj).forEach(function (Value) {
console.log(MyObj[Value]);
});
}
someMethod(1, MyObj);
This code (vanilla JS) will get the keys from the Object with Object.keys and allows you to iterate over it. Works for Objects and Arrays.
You can achieve that in the following way:
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
function someFunction(id, obj){
var objArray = $.map(obj, function(el) {
console.log(el);
return el
});
}
someFunction(1, MyObj)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The ExtJs way
ExtJs provides Ext.Object.eachValue which is what you are searching for.
From the ExtJs documentation:
Iterates through an object and invokes the given callback function for
each iteration. The iteration can be stopped by returning false in the
callback function.
The following code iterrates over each value of MyObj and calls the callback with it.
var MyObj = {
country : "Aus",
Time : "EST",
Val : "Pecific"
}
Ext.Object.eachValue(MyObj, function (Value) {console.log(Value)});
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' }
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Self-references in object literal declarations
Given this object:
var OBJ = (function(){
var dom = {
prop1 : 'something',
prop2 : 'something',
prop3 : prop1
}
return dom.prop3;
})();
How would i go to achieve the prop3 reference (ideally without creating a method) ? i tried:
this.prop1, dom.prop1, this.dom.prop1
You can't access the properties of an object before you have finished creating it. Create the object, then assign additional values.
var dom = {
prop1 : 'something',
prop2 : 'something'
};
dom.prop3 = dom.prop1;