I have a Javascript object and I’m struggling mightly to check in a loop if postsome is undefined.
Here is my object:
var indices = [{
"indexAB": [{
"postsome": [
"keyword_abc",
"keyword_def"
]
}]
},{
"indexA": [{
"postsome": [
"keyword_abc"
]
}]
}
]
Problem is, I can’t reference indexA,indexAB or postsome directly. All will be variables. This is what I’m trying:
// passed parameter
var doc._id = "postsome";
// mapping priv
// "indices": [
// {"name":"indexA","fields":["findMeA"]},
// {"name":"indexAB", "fields":["findMeA","findMeB"]}
// ],
for (var i = 0, l = indices.length; i < l; i += 1) {
var index = priv.indices[i];
index_name = index["name"]; // indexAB or indexA
// I can't reference indexAB directly
if ( indices[i].indexAB !== undefined && indices[i].indexAB.length > 0 ) {
console.log( indices[i].indexAB );
console.log( indices[i].indexAB[0][doc._id] );
if (indices[i].indexAB[0][doc._id] !== undefined) {
console.log("gotcha");
trigger = true;
}
}
}
So when I use indexAB hardcoded it works, but I need to loop through the values (‘indexA’ and ‘indexAB’ instea).
Question:
Is there any way to replace .indexAB[0] with a variable? If so, how?
Thanks!
Just use bracket notation, the exact same way you do with
[doc._id].Bracket notation and dot notation are interchangable, so these two lines are equivalent:
If you need to use a variable, however,
indices.varNamewould translate toindices["varName"], so you must use bracket notation to ensure that it uses the variable value instead of the variable name as a string.