I have an object:
obj = {
obj1: {
name: "Test";
}
}
and function:
var anon = function(a) {
alert(obj.a.name);
}
I want to give as an argument "obj1". Im newbie to programming so I think I should get alert with "Test" but it doesn't work. How to give reference with argument?
You can do this way: You can always access properties of the object as obj[key], thats what we are doing here.
var anon = function(a) {
alert(obj[a].name);
}
and remove ; from the inline object property definision syntax.
obj = {
obj1: {
name: "Test"; //<-- Here
}
}
http://jsfiddle.net/RuCnU/
This Link can provide you some basic insight on object and keys.
var anon = function(a) {
alert(obj[a].name);
}
When you are looking up the property of an object using a string use square brackets, the obj.a will only work if the object has a property named a, for example obj = {a: "Test"}.
Related
Is there a way I can get a property`s name inside the property itself?
I mean something like this:
let myObj = {
myProperty: {
name: <propertyName>.toString()
}
};
console.log(myObj.myProperty.name); // Prints `myProperty`
No, there isn't. There's nothing available when the object initializer is evaluated that provides that information.
Presumably if this were a one-off, you'd just repeat the name. If it's not a one-off, you could give yourself a utility function to do it:
// Define it once...
const addProp = (obj, name, value = {}) => {
obj[name] = value;
value.name = name;
return obj;
};
// Then using it...
let myObj = {};
addProp(myObj, "myProperty");
addProp(myObj, "myOtherProperty", {foo: "bar"});
console.log(myObj.myProperty.name);
console.log(myObj.myOtherProperty.name);
Say I have a function. If I wanted to add it as a method to an object, I would use:
let foofunc = function() {}
{
foo: foofunc
}
However, what if I want to add it as a getter? You'd think I could do it like this:
{
get x: foofunc
}
but my IDE complains, so I assume that's not possible. How would I do this?
You can use the Object.defineProperty function like so:
function getterFunc() { return 1; }
let anObject = {};
Object.defineProperty(anObject, 'propertyName', {get: getterFunc});
Live Example:
function getterFunc() { return 1; }
let anObject = {};
Object.defineProperty(anObject, 'propertyName', {get: getterFunc});
console.log(anObject.propertyName); // 1
You can access use the getter normally by doing anObject.propertyName.
The MDN page has more detailed information if you still have more questions.
To make it as getter function..
let foofunc = function() { return this.x;}
let obj = {
x: "marvel",
get foo(){return foofunc.call(this)}
};
use:
console.log(obj.foo);
I have the following Object
{
a: "123"
b: "$a"
}
b should always have the value of a.
Any idea of how I can make it with JavaScript?
You could use a getter method for the property b with an object.
var obj = {
a: "123",
get b() {
return this.a;
}
};
console.log(obj.b);
Otherwise, you are looking for an ES6 feature, Proxy
The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
Then take the prop and check if the value contains a $ and return this value of this property.
var obj = { a: "123", b: "$a" },
p = new Proxy(obj, {
get: function(target, prop) {
return target[prop][0] === '$' ? target[target[prop].slice(1)] : target[prop];
}
});
console.log(p.b);
If you're meaning a real JavaScript object you can do this with a getter and a setter via Object.defineProperty().
Or you can create a "class"
var obj= new function()
{
this.a=1212,
this.b=this.a
}
console.log(obj.b)
I was wondering if it's possible in Javascript for an object property to have the following behaviour:
console.log(obj); // output 'Something'
console.log(obj.prop_a); // output 'A'
And also
var a = obj; // a === 'Something'
var b = obj.prop_a; /// b === 'A'
The object kind of have two versions, one when you access it directly, and one when you access one of it's children props
Thanks
Yes, you can override toString() method:
obj.toString = function() {
return "Something";
}
If you need this to work in the browser, you would have to hook the console, as well as override the toString method of the object.
You could hook the browser console, and redefine it afterwards:
var obj = {
prop_a: "A",
toString: function() {
return "Something";
}
};
var origConsole = console;
console = {
log: function(data) {
if (typeof data === "object") {
origConsole.log(data.toString());
} else {
origConsole.log(data);
}
}
}
console.log(obj);
I have been looking around for an answer to this but in vain.
I have a function which takes a table name as an argument. but this name can be an object.
loadDataFromServer = function(dataTable) {
//data fetch code ...
datadump[dataTable] = response.getDataTable();
}
loadDataFromServer(['gchart']['data'])
The problem is I need to store the data in a variable datadump.gchart.data but the "gchart.data" part needs to be determined upon calling the function, not hard coded in it.
my problem lies in the fact that
datadump[['gchart']['data']] is not the same as
datadump['gchart']['data'] (which is the same as datadump.gchart.data)
Does anybody here know a good way to do this? If the input was simply gchart_data, this would easily work, but the functions needs to able to handle it even if it needed to assign its data to blabla.blibli.bloebloe.stuff.
thanks in advance
I think what you're looking for is this:
function (result) {
datadump = {};
datadump.gchart = {};
datadump.gchart.data = result.gchart.data;
// or
datadump.gchart = {
data: result.gchart.data
};
}
It's a little bit strange to it like this though. Do you absolutely need the gchart in your datadump?
Assigning to a random depth like blabla.blibli.bloebloe.stuff is not easily done.
You could flatten like: obj["blabla.blibli.bloebloe.stuff"] = {};
Or you could write a recursive merge, like:
var a, b, c;
a = { foo: { ipsum: "lorem" } };
b = { bar: {}, foo: { abc: "def" } };
c = recursive_merge(a, b); // { foo: { ipsum: "lorem", abc: "def" }, bar: {} };
Have you function take a list of strings and iterate over them to recursively access (and, if necessary, create) properties of datadump. I use arguments here to use the list of arguments itself, but you could also just use a single argument that is an array of strings.
var loadDataFromServer = function() {
var currObj = datadump;
// iterate over the list of property names
for(var i=0; i<arguments.length - 1; ++i) {
var nextName = arguments[i];
// if the object doesn't have this property, make it
if(currObj[nextName] == undefined) {
currObj[nextName] = {};
}
// use currObj's property as the new `currObj`
currObj = currObj[nextName];
}
// load data into the final named property
currObj[arguments[i]] = response.getDataTable();
}
loadDataFromServer('gchart', 'data');