Looped Object Arrays
I am trying to concatenate all my arrays inside an object and then check if the object inside the array has an imageUrl set if not. Then set it as default.
portfolio [i] returns undefined.
that.portfolio = {
applications = [
{ imageUrl: "" }
],
websites = [
{ imageUrl: "" }
]
}
var setDefaultImage = function () {
var portfolio = that.portfolio;
var defaultImageUrl = "App/Main/images/shared/defaultImg64x64.png";
for (var i = 0; i < Object.keys(portfolio).length; i++)
portfolio[i].forEach(function (currentObj) {
if (!currentObj.imageUrl) {
currentObj.imageUrl = defaultImageUrl;
}
});
}
+3
user1973285
source
to share
1 answer
portfolio
is an object, not an array, so the correct way to loop it would be for-in
loop:
for (var key in portfolio) {
portfolio[key].forEach(function(currentObj) {
if (!currentObj.imageUrl) {
currentObj.imageUrl = defaultImageUrl;
}
});
}
As you can see, there is no need to assign it here Object.keys(portfolio)
, but you can also use it if you like:
var keys = Object.keys(portfolio);
for (var i = 0; i < keys.length; i++) {
portfolio[keys[i]].forEach(function (currentObj) {
if (!currentObj.imageUrl) {
currentObj.imageUrl = defaultImageUrl;
}
});
}
0
source to share