Alexey Ayzin
Alexey Ayzin

Reputation: 209

Value Validation

Data:

var dataArr = [
    {id: 123, str:"Alexey Ayzin", bg:"#FFFFFF"},
    {id: 234, str:"Mira Mdivani"},
    {id: 345, str:"Maria Iliakova"},
    {id: 456, str:"Dennis Ayzin"}
];

As you can see, bg:"FFFFFF" exists in one of the subsets, but not the others. How can I change this:

for (var i = 0; i < datalength; i++) {
    if(dataArr[i].bg === "undefined"){
        data[i].bg = stringToColour(dataArr[i].str);
    }
}

So that it checks each subset for the existence of a BG and if it doesn't exist, fills it with one. JSFiddle

Upvotes: 4

Views: 80

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386680

You could use the in operator, if you have falsy values, which are valid.

if (!('bg' in dataArr[i])) {
    // set dataArr[i].bg
}

Upvotes: 1

Alexey Ayzin
Alexey Ayzin

Reputation: 209

What I ended up doing was the following:

for(var elem in payload.data){
    var isPresent = 0;
    for(var key in payload.data[elem]){
        if(key == "bG"){
            //change boolean if bG is present
            isPresent = 1;
        }
    }
    if(!isPresent){
        bGHex = stringToColour(payload.data[elem].str);
        payload.data[elem].bG = bGHex
    }

and then the rest of my code. This worked extremely well, especially after digging deeper into the logic of it.

Upvotes: 0

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11940

If item has bg, don't do anything, else - set new bg

var dataArr = [
    {id: 123, str:"Alexey Ayzin", bg:"#FFFFFF"},
    {id: 234, str:"Mira Mdivani"},
    {id: 345, str:"Maria Iliakova"},
    {id: 456, str:"Dennis Ayzin"}
];
dataArr.forEach(function (item){
    item.bg = item.bg || '#FFFFFF';
});

function assignColor(arr, prop, color){
    arr.forEach(function (item){
        item[prop]= item[prop] || color;
    });
}

// usage
assignColor(dataArr, 'bg', '#FFFFFF'); // <== or any other color

// UPDATE
//----------------------------

// get first value of color from array and assign to other
var item = dataArr.find(function(item){ // this will find first item which has defined color
    return !!item.bg;
});
assignColor(dataArr, 'bg', item.bg);

Upvotes: 2

Related Questions