parse value from array of object: error undefined is not iterable - javascript

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
}
}

Related

React: Properties change to undefined after updating a property in an array of objects

What I was trying to do is just updating a property in an object in an array and update the array state.
But all the properties change to undefined except for the one that has been updated after updating the object.
Code is like below.
let copyOfItems = [...items];
console.log(copyOfItems[currentIndex].propertyA); // a Value
const updatedItem = {
...copyOfItems[currentIndex],
propertyB: "newVal"
};
console.log(updatedItem.propertyA); // undefined
console.log(updatedItem.propertyB); // newVal
copyOfItems[currentIndex] = updatedItem;
setItems(copyOfItems);
What is wrong with this?
Why not try it this way to see how it works?
let copyOfItems = [...items];
console.log(copyOfItems[currentIndex].propertyA); // a Value
copyOfItems[currentIndex]['propertyB'] = 'new val'; // yes this is valid
console.log(copyOfItems[currentIndex].propertyA); // this should not be undefined
console.log(copyOfItems[currentIndex].propertyB); // newVal
setItems(copyOfItems);

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 {}

How to handle undefined object property in angular 5

I tried to fix the undefined error by setting the object property value to an empty string but its still giving the error as mentioned below:
ERROR TypeError: Cannot read property 'notes' of undefined
TS
let notes;
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
notes = '';
} else {
notes = manufacturer_field.manufacturer_guidelines[0].notes;
}
HTML
<p *ngIf="field.notes?.length">{{field.notes}}</p>
I referred this answer but that didn't work: How to handle 'undefined' in javascript
If notes array element 0 is undefined, then this will throw an error:
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
because you are checking if the property is undefined, when what is actually undefined is the .manufacturer_guidelines[0] item.
instead, you can do:
if (!manufacturer_field.manufacturer_guidelines[0]){
manufacturer_field.manufacturer_guidelines[0] = (assign it whatever value belong to this sort of item, and then once you know it is valid, then add notes)
}
Also, you are assigning the string to "notes" variable, not the actual array item.
So lets say i had a cars array:
if (!cars[0]) {
cars[0] = <Car>{};
cars[0].color = "blue";
}

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

Get array from a multidimensional object

I'm trying to grab the classes array based an id from the object. (and store it)
const objs = {
"1":{
"name":"Candice",
"classes": [00029,00023,00032,000222],
"id":0002918
},
"2":{
"name":"Clark",
"classes":[000219,00029,00219],
"id":00032
}
}
const objsKeys = Object.keys(objs);
const userClasses = objKeys.find(a => objs[a].id === this.state.userId).classes
console.log(userClasses);
// expect output
[00029,00023,00032,000222]
// but returns
Uncaught TypeError: Cannot read property 'classes' of undefined
What am I doing wrong here? Thank you for your help in advance!
You are getting the property name using Array#find method, and you are trying to get classes property of string and which is undefined . So you need to get the property value from object using the property name returned by Array#find method.
const userClasses = objs[objKeys.find(a => objs[a].id === this.state.userId)].classes
You are only getting the key.
Try:
const objs = {
"1":{
"name":"Candice",
"classes": [00029,00023,00032,000222],
"id":0002918
},
"2":{
"name":"Clark",
"classes":[000219,00029,00219],
"id":00032
}
}
const objsKeys = Object.keys(objs);
//if you console.log the following, you get the property/key of 2:
console.log(objsKeys.find(a => objs[a].id === 00032))
// you need to use that property to get the object value
const userClasses = objs[objsKeys.find(a => objs[a].id === this.state.userId)].classes
console.log(userClasses);

Categories