Avant Baker
Avant Baker

Reputation: 23

Iterating over an Object to verify if it's keys exist in an Array

Heres the situation -

I have an Array and an Object.

say:

var Array = ["field1", "field2", "field3"];
var Object = { field1: undefined, field2: undefined, field3: undefined, field4: undefined, field5: undefined}

*the values in the object don't really matter right now

Using underscoreJS i want to iterate over the Object and check to see if each of the keys exists in the Array array. If it does i want to be able to set its value to true and if not i want to set it to false.

So far i've tried:

 _.mapObject(Object, function(val, key){

        for (var j = 0; j < Array.length; j++) {
            currentKey = Array[j];
            (function(i){
                for (var k = 0; k < Array.length; k++) {
                    if(key === Array[i]) {
                        return val = true;
                    } else {
                        return val = false;
                    }
                }
            })(currentKey);
        }

    });

Shit is very confusing; for me at least. Any help is appreciatated.

Upvotes: 2

Views: 1517

Answers (4)

Gruff Bunny
Gruff Bunny

Reputation: 27986

Here's a solution using underscore:

    var result = _.mapObject(Object, function(value, field){
        return _.contains(Array, field);
    });

or if you want to change Object itself:

    var result = _.each(Object, function(value, field){
        return _.contains(Array, field);
    });

Upvotes: 1

ste2425
ste2425

Reputation: 4806

As others have said there's no need for underscore.

You can use the native Object.keys to return an array of own keys then iterate over them. Object.keys will not include inherited properties from the prototype chain which for in will. It is however considerably slower which could be a problem with large data-sets.

Object.keys(obj)
    .forEach(function (key) {
        obj[key] = (arr.indexOf(key) !== -1);
    });

Fiddle

Object.keys

Upvotes: 1

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21522

I don't think you need underscore for this:

var a = ["field1", "field2", "field3"];
var o = { field1: undefined, field2: undefined, field3: undefined, field4: undefined, field5: undefined}

for (var k in o) {
  o[k] = a.indexOf(k) != -1;
}

Upvotes: 1

t1m0n
t1m0n

Reputation: 3431

You don't need underscore to do this:

var arr = ['a','b','c'],
        obj = {a: '', b: '', c: '', d:''};

function check (a, o) {
    for (var key in o) {
        if (a.indexOf(key) != -1) {
            o[key] = true
        }
    }
}

check(arr,obj);

document.write(JSON.stringify(obj))

Upvotes: 0

Related Questions