Dynamically adding properties to an object - javascript

I have an object named Object1 which is third party object & I'm putting in properties inside it.
Object1.shoot({
'prop1':prop_1,
'prop2':prop_2,
'prop3':prop_3
});
Now I want the key 'prop1' to be added as property to Object1 only when prop_1 has some value. Otherwise I do not want to add it,
Whats the best way to do it?

You can check each property in for loop first.
var params = {
'prop1':prop_1,
'prop2':prop_2,
'prop3':prop_3
};
for (var param in params) {
if (typeof params[param] === 'undefined') {
delete params[param];
}
}
Object1.shoot(params);

You can make a helper function to add the property if defined:
function addProp(target, name, value) {
if(value != null) {
target[name] = value
}
}
var props = {}
addProp(props, 'prop1', prop_1)
addProp(props, 'prop2', prop_2)
addProp(props, 'prop3', prop_3)
The above does a null check instead of an undefined check. You can change as appropriate (e.g. you might not want empty strings, or number zero or anything else), though check this first:
How to determine if variable is 'undefined' or 'null'?

Related

Javascript reserved word and object

I'm making a dictionary of words, so there are 1,000,000+ words.
The problem comes when I need to store the word constructor. I know this is a reserved word in javascript, but I need to add it to the dictionary.
var dictionary = {}
console.log(dictionary ['word_1'])
//undefined, this is good
console.log(dictionary ['word_2'])
//undefined, this is good
console.log(dictionary ['constructor'])
//[Function: Object]
// this cause initialization code to break
How can I fix this? I could muck with the it like key=key+"_" but that seems bad. Is there anything else I can do?
Instead of using a JS object, you could use the built-in Map type which uses strings/symbols as keys and does not conflict with any existing properties.
Replace
var dictionary = {} with var dictionary = new Map()
Override the constructor key as undefined
According to the MDN Object.prototype page, the only thing that isn't hidden by the __fieldname__ schema is the "constructor field". Thus, you could just initialize your objects via { 'constructor': undefined }.
However, you would have to make sure that in your for .. in statements would filter out all keys with undefined as their value, as it would pick up constructor as a "valid" key (even though it wouldn't before you specifically set it to undefined). I.E.
for(var key in obj) if(obj[key] !== undefined) { /* do things */ }
Check for types when getting/setting
Otherwise, you could just check the type when you 'fetch' or 'store' it. I.E.
function get(obj, key) {
if(typeof obj[key] !== 'function') // optionally, `&& typeof obj[key] !== 'object')`
return obj[key];
else
return undefined;
}
I think you should store all words and translation of them in an array. When you need to translate a word, you can use find method of Array.
For example:
var dict = [
{ word: "abc", translated: "xyz" },
...
];
Then:
var searching_word = "abc";
var translation = dict.find(function (item) {
return item.word == searching_word;
});
console.log(translation.translated);
// --> xyz
To achieve expected result , use below option of using index to get value of any key value
var dictionary = {};
var dictionary1 = {
constructor: "test"
};
//simple function to get key value using index
function getVal(obj, val) {
var keys = Object.keys(obj);
var index = keys.indexOf(val);//get index of key, in our case -contructor
return obj[keys[index]]; // return value using indec of that key
}
console.log(getVal(dictionary, "constructor"));//undefined as expected
console.log(getVal(dictionary1, "constructor"));//test
console.log(dictionary["word_1"]);
//undefined, this is good
console.log(dictionary["word_2"]);
//undefined, this is good
codepen - https://codepen.io/nagasai/pen/LOEGxM
For testing , I gave one object with key-constructor and other object without constructor.
Basically I am getting the index of key first and getting value using index

Update a javascript object using non undefined properties

I've got a function to update an object:
_.each(user, function(value, key, obj) {
if (user[key] !== undefined) {
self.user[key] = user[key];
}
});
It lets me update users like this:
let user = new User();
user.verified = true;
self.sessionService.updateSession(user);
I only need to specify properties that are going to be updated by checking for undefined, can this be simplified or written more efficient?
You could do something like this using underscore:
_.assign(self.user, _.omit(user, _.isUndefined))
This works by creating an object where all the keys with undefined values are omitted using omit and the isUndefined predicate.
This object is then used with assign to update the self.user object.
I'm not sure if this is the answer you need, but you can set a variable to new value if it's undefined/null/"" like this:
myVar = myVar || newValue;
If myVar is defined, the old value will be kept. If not, it will be assigned to newValue.

Jquery/javascript creating object

So, I want to create an object (semi-automatically) using Jquery.
Instead of posting all of my code here, I'll give an example of what I want to do:
var myobject = {
'name1': {
'coord1':true,
'coord2':false,
'coord3':false,
},
'name2': {
'coord4':true,
'coord5':false,
'coord6':false,
}
}
1) I first want to check if 'nameX' is already in my object, if so, continue to step 2, if not, I want to add the name, and coordX with value true or false.
2) If 'nameX' is in the array, I want to check i 'coordX' is in the array. If so, I need to check if the corresponding value (true or false) is the same, and if not, replace it. If 'CoordX' is not in the object, I want to add it with the corresponding value.
For example:
var mynewname = 'name3';
var mynewcoord = 'coord5';
var mynewvalue = 'true';
var mynewname2 = 'name1';
var mynewcoord2 = 'coord4';
var mynewvalue = 'false';
When checking these values with the object this should give:
var myobject = {
'name1': {'
coord1':true,
'coord2':false,
'coord3':false,
'coord4':false
},
'name2': {
'coord4':true,
'coord5':false,
'coord6':false
},
'name3':{
'coord5':true
}
}
I hope someone can help me with this. Thank you
In order to find out if an object contains a property with a given name, you have a couple of choices.
You can use the in operator with a string property name:
if ("nameX" in myobject) {
// The object referenced by `myobject` (or its prototype)
// has its own property called "nameX"
}
else {
// It doesn't
}
in will check the object and its prototype. That probably doesn't matter for the simple objects you're using.
Or you can use hasOwnProperty, which only checks the object and not its prototype:
if (myobject.hasOwnProperty("nameX")) {
// The object referenced by `myobject` has its own property called "nameX"
}
else {
// It doesn't
}
So for instance, if you want to see if name1 is in myobject and, if not, add name1 referencing a blank object, you'd do this:
if (!("name1" in myobject)) {
myobject.name1 = {}; // No, add it and give it a blank object as its value
}
And similarly for the coordX properties of the objects you're referencing from myobject.nameX.

What does this JavaScript notation do: Object[key](value)

I'm not really sure what's going on here, but in a nutshell I've seen this:
Object[key](value);
In line 1088 of bootstrap-datetimepicker:
$.fn.datetimepicker = function ( option, val ) {
return this.each(function () {
var $this = $(this),
data = $this.data('datetimepicker'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('datetimepicker', (data = new DateTimePicker(
this, $.extend({}, $.fn.datetimepicker.defaults,options))));
}
// Line below:
if (typeof option === 'string') data[option](val);
});
};
Would anyone be able to answer what is going on?
I thought maybe it was assigning the value to the key in the object but when I tried doing something similar in the developer console (working in chrome v.33) it doesn't work.
Object is a Javascript object that you can declare like this:
var obj = {};
Then a property is created (whose name is contained in the key variable) with a function as its value:
var obj['myfunction'] = function() { alert('Hello!'); };
So now,you have a function stored in your object 'obj' in the 'myfunction' key.
Since it's a function you execute it using '()', which results in:
obj['myfunction']()
var property = 'method';
// multiple ways to access properties
object.method === object['method'] === object[property];
// and you can use any syntax to call the method
// These all call `object.method`:
object.method() === object['method']() === object[property]();
See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators
To access properties of an object in JavaScript you can either use the dot notation. i.e: Object.property or the string notation (also called bracket notation) Object[property].
Both are valid, though the dot notation doesn't work with property names containing spaces for example, such as Object.property name is invalid, while Object['property name'] is valid.
Given your example, Object[key](value) you are accessing a property of which the name is stored in the key from the Object object. The property happens to be a method and you can execute it passing value as the parameter.
Imagine the object to look like this:
Object = {
myProp: function(newValue){
// do something with newValue
}
}
It would be perfectly fine to call it using the string notation if the method name is stored in a variable:
var key = 'myProp';
Object[key](value);
or if you don't need a variable you can also call it directly using the dot notation:
Object.myProp(value);
Resources: MDN on Property Accessors
Maybe just a hack to do something like:
var method = "create";
var prop = new String();
var str = Object[method](prop);
So you invoke a method create with parameter prop.

Looping through object in JavaScript

if(properties != undefined)
{
foreach(key in properties)
{
dialogProperty.key = property[key];
}
alert(dialogProperty.close);
}
How can I achieve/fix the above code? I think the above code is self explanatory.
I think you mean for rather than foreach. You should also stop key being global and use Object.prototype.hasOwnProperty:
if(properties != undefined)
{
for (var key in properties)
{
if (properties.hasOwnProperty(key) {
dialogProperty[key] = properties[key]; // fixed this variable name too
}
}
alert(dialogProperty.close);
}
NB Incorporated Kobi's fix too.
Assuming you're trying to copy all properties, you're probably looking for:
dialogProperty[key] = property[key];
dialogProperty.key is not dynamic, it sets the key property each time, the same way dialogProperty["key"] would.
properties && Object.keys(properties).forEach(function(key) {
dialogProperty[key] = properties[key];
});
console.log(dialogProperty.close);
The properties && check is to ensure that properties is not falsy.
The Object.keys call returns an array of all keys that the properties object has.
.forEach runs a function for each element in the array.
dialogProperty[key] = properties[key] set's the value of dialogProperty to be that of properties.

Categories

Resources