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 {}
Related
I would like to get the value from array under of object and also provide some error checking. I have following code to check if key exist and if value of key is array type or not. if yes, I would like to get the value from the key. it seems ok, but any better way I can get value? I tried to use const [value] = obj?.the_key but get exception Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) if
value from the_key is not array or the_key does not exist under object
const obj = {'theKey': ['correct value']}
const hasKey = obj['theKey'] !== undefined && Array.isArray(obj.theKey)
if (!hasKey) console.log('null')
const [value] = obj.theKey
console.log(value)
You can use the hasOwnProperty and isArray functions to check if your object has the key / property that you are looking for.
const obj = { 'theKey' : ['correct value'] };
let hasKey = obj.hasOwnProperty('theKey'); // This will return true / false
if (!hasKey) { // key does not exist
// error handling logic
}
Then you can check the data type of the value if it is array or not
if (hasKey) {
let keyVal = obj.theKey;
if (Array.isArray(keyVal)) { // returns true or false
// business logic with array
} else { // key value is not array
// error handling
}
}
I'm trying to add an array as a property to an object in its constructor, like so:
let object {
entries = [],
}
But when I try to access the "entries" property, either inside a function of the object itself, or in an outside function, it isn't recognized as an array.
I think you just have a syntax error in constructing the object, there shouldn't be any issue accessing an array in an object:
let object = {
entries: [],
getEntries() {
return this.entries;
}
}
object.entries.push('it works');
console.log(object.entries)
console.log(object.getEntries())
I'm very new to JavaScript. I was trying pushing new values to an object. But when I tried to push an array that doesn't exist in myObj, I got Cannot read property 'push' of undefined error.
My code is below:
var myObj = {
first: "first value",
second: "second value",
}
myObj.third.push(123)
console.log(myObj)
But when I check if it doesn't exist and create an empty array, then push it, it works. =>
var myObj = {
first: "first value",
second: "second value",
}
myObj['third'] = myObj.third || []
myObj.third.push(123)
console.log(myObj)
I wonder if bottom code is best practice and if there is a better way to do it.
The push method is part of the Array prototype in your particular case you are trying to access a not defined property which in JavaScript is consider undefined so you are trying to do transalates into something like:
myObj.third.push => myObj.undefined.push
Because myObj does not have a third key you can try this in the console doing console.log(myObje.third );
So the engine returns an error saying that undefined does not have a property push that is only available in Array.
In this case you need to set assign a value to myObj.third before using it as an array, for that there are multiple ways to set the value as an array your answer above is one of those ways:
myObj['third'] = myObj.third || []
That line works however if for example myObj.third has a value will use that as a value as you are assigning the result of the operation myObj.third || [] which in this scenario anything that evaluates as truthy will be returned if for instance you have:
myObj.third = true;
And then you do:
myObj.third.push(123);
An error will be displayed Uncaught TypeError: myObj.third.push is not a function as currently myObj.third is not an array.
So you need to make sure you are operating over an Array when using push, or at least when you initialize the value of your property is set as an Array, you can find more details on Array construction on this page.
Alternatives you can do to check before pushing are:
if ( ! Array.isArray(myObj.third) ) {
myObj.third = [];
}
myObj.third.push(123)
Updated 2nd:
You could do a ternary operator
let myObj = {
first: 'first value',
second: 'second value'
};
myObj.third = myObj.third ? [...myObj.third, 123] : [123];
console.log(myObj);
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}
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