needhelp
needhelp

Reputation: 13

remove key where value is false in javascript

I have an array with a structure similar to the one shown.

var a = {};
a['key1'] = 'false';
a["key2'] = 'true';
a['key3'] = 'false';
a['key4'] = 'false';
a['key5'] = 'true';

I want to remove any entry with a value of false, resulting in an array as shown.

{key2:true, key5:true}

I can easily do this in php using array_filter, but I cant figure out the js equivalent. The nearest suggestion Ive found through searching is

for (var key in array) {
    if (array[key] == false) {
        array.splice(key, 1);
    }
}

but I can't get it to work.

Upvotes: 1

Views: 1356

Answers (3)

Beginner
Beginner

Reputation: 4153

try this

    for (var key in a) {
        if (a[key] == 'false') {
            delete a[key];
        }
    }

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You need to iterate over the keys and delete the properties.

var object = { key1: false, key2: true, key3: false, key4: false, key5: true };

Object.keys(object).forEach(function (key) {
    if (object[key] === false) {
        delete object[key];
    }
});

console.log(object);

Upvotes: 2

Darin Cardin
Darin Cardin

Reputation: 657

Create a new array. Add just the ones you that fit your criteria:

                   var array = [true,false,true, true   ]

                    var newArray = [];

                    for(var key in array){
                        if(array[key] != false) 
                            newArray.push(array[key]) ; 
                    }

Upvotes: 0

Related Questions