I have the following function which takes in an object as an argument and uses it to manipulate the object
function manipulateData(obj){
var data = Object.keys(obj).forEach(function(index){
//Perform the manipulation
return obj;
}
return data;
}
I invoke the above function in another callback function, as following
converter.on('done', function(jsonArray){
var newObj = manipulateData(jsonArray);
});
Upon debugging i notice that the value returned from the forEach is "undefined", how can i get the data to be returned as expected?
The "Cannot read property 'forEach' of undefined" error occurs when calling the forEach method on an undefined value. To solve the error make sure to initialize the variable to the correct value and only call the forEach method on the correct data type.
Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object . The ordering of the properties is the same as that given by looping over the properties of the object manually.
You can't exit a forEach Loop, So Use every() Instead Once it's started, it will run until it reaches the last item in the array.
forEach() executes the callbackFn function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.
The "Cannot read property 'forEach' of undefined" error occurs when the forEach () method is called on an undefined value. To solve the error, make sure to only call the forEach method on arrays, Set or Map objects. Here is an example of how the error occurs. Copied! Because we called the forEach method on an undefined value, we got the error back.
Use the Object.keys () method to get an array of the object's keys. Use the forEach () method to iterate over the array and delete all undefined values using the delete operator. Copied! The Object.keys method returns an array containing the object's keys.
Now the forEach itself works just fine when executed by itself in the console - but as soon as I want to return it, it equals undefined. What am I missing? Because forEach does not create a new object. It doesn't have a return value. You could simply return testArray; since you are mutating that object. Of course you can't return from forEach.
The Object.values () function returns an array of the object's own enumerable property values. In other words, it returns an array over the object's values that you can iterate through using forEach (). The Object.entries () function returns an array of entries.
forEach
doesn't return anything. If you want to make a new Array
by transforming the existing one, use map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With