adding a property to an object in javascript - javascript

function addProperty(object, property) {
// add the property to the object with a value of null
// return the object
// note: the property name is NOT 'property'. The name is the value of the argument called property (a string)
}
I got a little stuck on an only home work question. I think I understand what its asking me to do. I want to pass in an object and add a new property and set its default value to null.
Here is what I have tried doing
function addProperty(object, property) {
// add the property to the object with a value of null
// return the object
// note: the property name is NOT 'property'. The name is the value
object.property = property;
object[property] = null;
return object;
}
This does not seem to be working the way I need it to as I believe I the object should produce something like
const object = {
propertyPassedIn: null,
};
can anyone help or point me in the right direction?

This works for me
function addProperty(object, property) {
// add the property to the object with a value of null
// return the object
// note: the property name is NOT 'property'. The name is the value
// object.property = property;
object[property] = null;
return object;
}
var obj = {x:1,y:null};
// undefined
obj
// {x: 1, y: null}
addProperty(obj, 'z');
// {x: 1, y: null, z: null}

Just remove
object.property = property;
from your sample. This line would create a ReferenceError if the property is not already in the object. Other than that, I can't see a reason why it wouldn't do what you say you expect.

function addProperty(object, property) {
object[property] = null;
return object;
}
var obj = {
key1:1,
key2:2
};
addProperty(obj, 'value');
this will give below result
{key1:1, key2:2, value:null}

Related

How to add a new key and value in null object?

I have a null object. And I want to add dynamic key and object into that.
Tried
this.myObj[`${dayValue}`] = {}; //1
this.withDayTimeSlot[dayValue] = [targetValue];
Error
TypeError: Cannot set property '5' of null at ...
My dynamic object will be look like this.
{
'5':[],
'6':[]
}
You cannot set properties in a null object. It needs to be initiated as an empty object {} first.
this.myObj = {};
this.myObj[`${dayValue}`] = []; // [] since your desired value in the object is an empty array [] and not an empty object {}

What is the Javascript equivalent of Python's get method for dictionaries

Python's get method for dictionaries lets me specify what should be returned if a key doesn't exist. For my current case I want a dictionary returned. How do I do this in Javascript?
There is no javascript equivalent of the python dictionary get method. If you would write it yourself, as a function, it would look like this:
function get(object, key, default_value) {
var result = object[key];
return (typeof result !== "undefined") ? result : default_value;
}
Use it like:
var obj = {"a": 1};
get(obj, "a", 2); // -> 1
get(obj, "b", 2); // -> 2
Note that the requested key will also be found in a prototype of obj.
If you really want a method rather than a function (obj.get("a", 2)), you need to extend the prototype of Object. This is generally considered a bad idea though, see Extending Object.prototype JavaScript
With modern javascript you can use the nullish coalescing operator ??
const result = obj[key] ?? default;
This will return the default value if key doesn't exist in obj. It will also return the default in cases like {myKey: undefined} or {myKey: null}, which may or may not be the desired behavior.
JavaScript has no helper feature to do that. You need to test explicitly.
if ("myProperty" in myObject) {
return { another: "object" };
} else {
return myObject.myProperty;
}
You can use a ternary operator to do the same thing with less code.
return ("myProperty" in myObject) ? myObject.myProperty : { another: "object" };
I prefer to use the logical OR like this:
foo.bar || 'default'
If checks is foo.bar is falsy, so it returns 'default' if bar is undefined.
You just need to care, that foo is an object. Otherwise a ReferenceError is thrown.
You could use a proxy for this (really new ):
var handler = {
get: function(target, name){
return name in target?
target[name] :
"Default";
}
};
var dictionary={"hi":true};
var dict = new Proxy(dictionary, handler);
dict.a = 1;
dict.b = undefined;
console.log(dict.a, dict.b,dict.hi); // 1, undefined,true
console.log(dict.new); //"Default"
//the proxied object gets changed:
console.log(dictionary.a, dictionary.b,dictionary.hi); // 1, undefined,true
console.log(dictionary.new); //undefined
A proxy is an object that reflects all changes and requests trough an handler. In this case we can write/access propertys of dictionary normally, but if we access values that do not exist it'll return "Default"
this works for me
let obj = {"a": 1};
let default = 100
obj["a"] || default; // -> 1
obj["b"] || default; // -> 100
But! there are some limitation, if !!obj["a"] === false we always get default value... so it's better to just check if key in obj, to be completely sure.

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

Assigning nested values in (partially) undefined objects

Say I want to assign a value like this:
x.label1.label2.label3 = someValue;
// or equivalently:
x['label1']['label2']['label3'] = someValue;
This works as long as x.label1.label2 is defined but runs into reference errors otherwise. Which makes sense of course. But is there an easy way to assign this anyway where it simply creates the necessary nested objects?
So for example, if x equals { label1: {}, otherLabel: 'otherValue' } I want to update x to become { label1: { label2: { label3: someValue } }, otherLabel: otherValue }
I think I might be able to write a function myself, but is there a language feature or standard library function that does this?
is there a language feature or standard library function that does this
No. You have to write your own function or use a library that provides such functionality.
Related: How to set object property (of object property of..) given its string name in JavaScript?
This is partially possible using the Proxy class. You can wrap your object in a Proxy and override the get trap to create another copy of the same proxy when you access a nonexistent property. This lets you recursively create "deep" properties. An example:
let traps = {
get: function (target, name) {
if (!(name in target))
target[name] = new Proxy({}, traps);
return target[name];
}
};
let x = new Proxy({}, traps);
Then you would use x like any object, except it has this special behavior:
x.label1.label2.label3 = 'foo';
which creates a nested hierarchy of objects. However, note that this will create an object even if you access a nonexistent property. Thus, you will have to use the in keyword to check if it really contains a given property.
I think you should indeed use a custom function such as:
function assignByPath(obj, path, value) {
var field = path.split('>'),
last = field.pop();
field.reduce(
function(node, f) {
return node[f] = node[f] instanceof Object ? node[f] : {};
}, obj
)[last] = value;
}
var myObj = {};
assignByPath(myObj, 'label1>label2>label3', 'someValue');
console.log(myObj);
Theoretically, you could also override Object.prototype, which would allow you to do:
myObj.assignByPath('label1>label2>label3', 'someValue');
But I would not recommend that.
You can use Array.prototype.shift(), Object.assign(), recursion
var x = {
label1: {},
otherLabel: "otherValue"
};
var nestprops = (props, value, obj, o, curr = props.shift()) => props.length
? nestprops(props, value, (Object.assign(obj, {[curr]: {}}) && obj[curr]), o)
: ((!value || value) && (obj[curr] = value) && o);
console.log(nestprops(["label1", "label2", "label3"], "someValue", x, x));
Check length of keys inside label1 object if its equal to 0 then modify it to your desired object.
Here is a snippet, hope it helps.
var obj = { label1: {}, otherLabel: 'otherValue' };
if(Object.keys(obj.label1).length == 0 ) {
obj.label1 = { label2: { label3: "value3" } };
}
console.log(obj);

Can you access a property of an object as a value in javascript?

var obj = { 'first':'1st', 'second':'2nd', 'third':'3rd', ...}
I know that accessing the value of an object's property is...
obj.first || obj["first"] //returns '1st' as a value
What I'm trying to figure out is how to access the property as a value without iterating through the whole var obj to make a new var that has the property switched with the value. It would just be a whole new obj.
Is this possible? Have I given enough context? I would appreciate any help.
Since an object is, well, an Object, you can pull the whole object keys into an Array, and then pull the one which is right for you..
Using the Object.keys() method you can access to the keys of your object, then, using the Array.indexOf() method you will pull which is right for you.
A Short Example
function getKey(obj, key) {
var arr = Object.keys(obj);
var result = '';
if (arr.indexOf(key) !== -1) {
var index = arr.indexOf(key);
result = arr[index];
return result;
}
return null;
}
var obj = {
'first': '1st',
'second': '2nd',
'third': '3rd'
}
console.log(getKey(obj, 'first'));
See:
MDN Object.keys() Ref.
A CodePen example
If i understand correctly you want to bind an objects property to another object's property so that when o1.first changes o2.first changes automatically. That would be possible with arranging the setter of o1.first property. A simple way to achieve this with object litereals would be like
var o1 = {
_first: "1st",
second: "2nd",
third: "3rd",
get first() {
return this._first
},
set first(v) {
this._first = v;
o2.first = v;
}
},
o2 = {first:""};
console.log(o1) // Object {_first: "1st", second: "2nd", third: "3rd"}
console.log(o2) // Object {first: ""}
o1.first = yes;
console.log(o1) // Object {_first: "yes", second: "2nd", third: "3rd"}
console.log(o2) // Object {first: "yes"}
o1["first"] = "once again"; // "once again"
console.log(o2["first"]); // "once again"
For more information on JS object getters and setters have a look at https://robertnyman.com/javascript/javascript-getters-setters.html

Categories