How to define object key using other object property value? - javascript

I have an object and I want to use object property value as key (simplified):
var App = function() {
this.settings = {
'tetris': {
title: 'Tetris'
},
'galaxian': {
title: 'Galaxian'
}
};
this.gameName = 'tetris';
this.request = {
this.settings[this.gameName].title: 'THIS KEY IS INVALID' // :(
}
};
I know I could assign it as:
this.request[ this.settings[this.gameName].title ] = 'Valid...';
But I wonder if I can define the property name using the object property value?

I am afraid, what you mean is not possible. You can not use a variable as a key in an object literal like this:
var key = "somekey";
var obj = {key: "value"}
The above code will result in an object that has the key key.
You can only use a variable to define an object element like this:
var key = "somekey";
var obj = {};
obj[key] = "value"
Then the object get's an element with the key somekey
EDIT: As stated in the comments, in ECMAScript 6 the support for computed properties in object literals got introduced. However the browser support for the computed properties in object literals is very slim (you can look it up here under syntax -> object literals). For example IE 11 has no support for it, neither has Chrome 43.

Computed property names will be introduced in ECMAScript edition 6, they're in the current draft, so you can do:
this.request = {
[this.settings[this.gameName].title]
}
They're reasonably well supported now, see MDN for more detail.

You can't define literal objects with computed property names; you have to assign them.
In other words, you can either define a literal object using {...} notation if the property name is well-known, or assign values into keys in a map using x[prop] = v notation if the property name is computed.
Think of your JS objects as being either objects or maps, but not both. If the JS object has well-known property names then it's acting as an object:
var obj = {
wellKnownPropertyName = 'value';
};
var value = obj.wellKnownPropertyName;
But if the property name is computed then it's not really a property of an object but more like a key in a map, and should be assigned (and read) as such:
var map = {};
var key = getUnknownKeyFromSomewhere();
map[key] = 'value';
var value = map[key];

Related

Create JSON object accoring to request.body

Using NodeJs + Express to create a REST API. Everything works well, but I can't understand how to iterate through the request.body and check its fields for undefined and empty values and assign new object only with valid data.
request.body looks like:
{
key: 'value',
otherKey: 'otherValue',
oneMoreKey: '',
oneMoreKey2: undefined,
oneMoreKey3: null
}
At that end my object shoud look like:
let contactData = Object.assign({},{
'key': 'value',
'otherKey': 'otherValue'
})
Looking for your advices and help
JavaScript
function getCleanObject(oldObject) {
var newObject = {};
for (var property in oldObject) {
var value = oldObject[property];
if (value) newObject[property] = value;
}
}
Explanation
You can start off by creating a new clean Object
var newObject = {}; // same as new Object();
Then iterate through all of the object's properties using a for loop.
for (var property in oldObject)
Then get the value of that property
var value = oldObject[property];
If the value is Troothy add the property to the new Object
if (value) newObject[property] = value;
Note that this way the false value will be rejected. To allow it to be copied to the new Object you should replace the if statement with
if(value || value === false)
Moreover, if the Object you are copying also inherits from some other Object it is possible that it will have extra properties as well and if you do not want them to be included you should change the if statement to
if(value && oldObject.hasOwnProperty(value))
And Remember for(var item in object) != for(var item of list)
in is used to iterate through an object's properties whereas of is used to iterate through an iteratable (i.e. list). Also in is supported in all browsers whereas of is not supported by internet explorer.
your_object = {
key: request.body[key] || 'default',
otherKey: request.body[otherKey] || 'default',
oneMoreKey: request.body[oneMoreKey] || 'default'
...
}
explanation on how or (||) works JavaScript OR (||) variable assignment explanation

What is function with brackets mean?

Does anyone know what is test[name] mean?
function test(value){
copy(value||{},this);
}
test[name] = function(){
return "test"
}
This will be easiest to explain with an example:
var name = "foo";
test[name] = function(){
return "test"
};
This would add a property named "foo" to the object test, and the value of that property is a function. It doesn't matter in this case that the object test is actually a function, you can assign properties to functions just like any other object in JavaScript.
You could call this function using any of the following methods:
test[name]()
test["foo"]()
test.foo()
Note that test[name]() will not work if the name variable is assigned to something different, for example name = 'bar'.
Javascript has two sets of notation for accessing objects, dot notation (obj.property) and bracket notation (object[property]). More on that at MDN.
test[name] = function (){} assigns an anonymous function to the name property on the the test object (which itself is a function). In this case (as noted by the comments) the variable name is being used to access the property.
This may seem a little strange at first, but it's helpful to remember that in javascript, functions are objects.
All functions in Javascript are also objects. This adds a property to the test function object with a value which is an anonymous function.
For example:
function test(){
return "foo";
}
// test is a function, so it is also an object and
// it can have properties assigned to it
test.x = function(){
return "bar";
};
test(); // "foo"
test.x(); // "bar"
Of course just like with any object you can also use bracket notation:
var name = 'hello';
test[name] = function(){
return "HELLO!";
};
test.hello(); // "HELLO!"
In JavaScript, functions are objects. They have properties. test[name] sets a property (named whatever the name variable holds) to a function.
when you have a javascript object with defined properties you can access the property either with the dot notation obj.property or with the square brackets notation obj[property]
the property could also be a function so if you have an object:
var test = {
foo : function(arg){ console.log(arg) },
bar : 'hello'
};
you can call test.foo('bar') also by doing test['foo']('bar')
This is especially useful in iterations or when you dont know a priori what the name of the property is going to be. For example:
var fun = 'foo';
test[fun]('hello world');
Naturally it's up to you to do proper checks such as
if ('function'==typeof test['foo']){ test['foo']('bar'); }
Also note that you can do checks on the fly like so:
test[ fun || 'foo']('hello');
Taken from the Mozilla page
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of object members
There are two ways to access object members: dot notation and bracket notation (a.k.a. subscript operator).
So
test[name] = function (
means: there are (if everything is ok) two objects: test and name (and we know that at least test is present, because you defined it one line before: function test(value))
take the test object (if there isn't a test object an error will happen). Then access the key/value pair with the key calculated from the name object and there put a function.
Now, how the key is calculated from the name object? The same page from before tells us:
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
Note that the description is a little wrong... test[null] == test["null"] and test[undefined] == test["undefined"], so perhaps the truth is that under the covers something like String(key).valueOf() is done (the String function will convert null to "null" and undefined to "undefined")
Some examples (where => means "is equivalent to, with this values")
var name = 'foo';
test[name] => test['foo']
var name = 123;
test[name] => test['123']
var name = 123.3;
test[name] => test['123.3']
var name = new Date();
test[name] => test['Wed Aug 14 2013 17:35:35 GMT+0200 (...)']
var name = null;
test[name] => test['null']
var name = undefined;
test[name] => test['undefined']
var name = [];
test[name] => test['']
var name = [1,2,3];
test[name] => test['1,2,3']
var name = {};
test[name] => test['object Object']
and so on...
The brackets are how you reference a property via a key into the hash that javascript objects are.

object Key in javascript class/dictionary?

I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object

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];
});

create object using variables for property name [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 7 years ago.
Is it at all possible to use variable names in object literal properties for object creation?
Example
function createJSON (propertyName){
return { propertyName : "Value"};
}
var myObject = createJSON("myProperty");
console.log(myObject.propertyName); // Prints "value"
console.log(myObject.myProperty); // This property does not exist
If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:
var foo = "bar";
var ob = { [foo]: "something" }; // ob.bar === "something"
If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):
Create the object first, and then add the property using square bracket notation.
var foo = "bar";
var ob = {};
ob[foo] = "something"; // === ob.bar = "something"
If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.
ES6 introduces computed property names, which allow you to do
function CreateJSON (propertyName){
var myObject = { [propertyName] : "Value"};
}
Note browser support is currently negligible.
You can sort of do this:
var myObject = {};
CreateProp("myProperty","MyValue");
function CreateProp(propertyName, propertyValue)
{
myObject[propertyName] = propertyValue;
alert(myObject[propertyName]); // prints "MyValue"
};
I much perfer this syntax myself though:
function jsonObject()
{
};
var myNoteObject = new jsonObject();
function SaveJsonObject()
{
myNoteObject.Control = new jsonObject();
myNoteObject.Control.Field1= "Fred";
myNoteObject.Control.Field2= "Wilma";
myNoteObject.Control.Field3= "Flintstone";
myNoteObject.Control.Id= "1234";
myNoteObject.Other= new jsonObject();
myNoteObject.Other.One="myone";
};
Then you can use the following:
SaveJsonObject();
var myNoteJSON = JSON.stringify(myNoteObject);
NOTE: This makes use of the json2.js from here:http://www.json.org/js.html
One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.
function func(prop, val) {
var jsonStr = '{"'+prop+'":'+val+'}';
return JSON.parse(jsonStr);
}
var testa = func("init", 1);
console.log(testa.init);//1
Just keep in mind, JSON property names need to be enclosed in double quotes.

Categories