I have the following loop structure that iterates over an array of object refs, does something for each defined object and should print out the name of the undefined object.
For that I need to print the actual object name that was passed into the iterator.
Is there any operator that provides name of the parameter passed into the iteratee function?
//couple of objects with some data
var a = { .... };
var b = { .... };
//undefined object
var c;
var d;
var e;
.
.
.
.
var someNthVar;
_.forEach (
[a,b,c,d,e,....],
function (obj) {
if (obj) {
//do something
} else {
//PROBLEM!!! How do i specify that variable 'c' is the one that is undefined
//log undefined variables
console.log('Undefined variable: ' + obj.variableName);
}
}
);
Is there any operator that provides name of the parameter passed into the iteratee function?
No. You can define a list of names and associate them by index, though:
const names = ['a', 'b', 'c'];
[a, b, c].forEach((obj, i) => {
if (!obj) {
throw new Error(`${names[i]} missing a value`);
}
// do something
});
Have you considered using a javascript object to hold your values?
That way you could write something like the following, using the similar forIn ;
var objects = {
a: {...},
b: {...},
c: undefined,
d: {...}
}
_.forIn(objects, function(value, name){
if (!value) {
throw new Error(`${name} is missing a value`);
}
// Do something
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.