binaryBigInt
binaryBigInt

Reputation: 1704

JavaScript - Filter <key,value> Object by key

I am looking for a short and efficient way to filter objects by key, I have this kind of data-structure:

{"Key1":[obj1,obj2,obj3], "Key2":[obj4,obj5,obj6]}

Now I want to filter by keys, for example by "Key1":

{"Key1":[obj1,obj2,obj3]}

Upvotes: 0

Views: 1248

Answers (4)

Alex Szabo
Alex Szabo

Reputation: 3266

Not sure what exactly are you trying to achieve, but if you want to have a set of keys that you would like to get the data for, you have quite a few options, one is:

var keys = ['alpha', 'bravo'];
var objectToFilterOn = {
  alpha: 'a',
  bravo: 'b',
  charlie: 'c'
};

keys.forEach(function(key) {
  console.log(objectToFilterOn[key]);
});

Upvotes: 0

CRice
CRice

Reputation: 32146

You can create a new object based on some custom filter criteria by using a combination of Object.keys and the array .reduce method. Note this only works in es6:

var myObject = {"Key1":["a","b","c"], "Key2":["e","f","g"]}

function filterObjectByKey(obj, filterFunc) {
    return Object.keys(obj).reduce((newObj, key) => {
        if (filterFunc(key)) {
            newObj[key] = obj[key];
        }
        
        return newObj;
    }, {});
}

const filteredObj = filterObjectByKey(myObject, x => x === "Key1")
console.log(filteredObj)

Upvotes: 0

Kenry Sanchez
Kenry Sanchez

Reputation: 1733

you can use the .filter js function for filter values inside an object

var keys = {"Key1":[obj1,obj2,obj3], "Key2":[obj4,obj5,obj6]};

var objectToFind;

var keyToSearch = keys.filter(function(objects) {
  return objects === objectToFind
});

The keyToSearch is an array with all the objects filter by the objectToFind variable.

Remember, in the line return objects === objectToFind is where you have to should your statement. I hope it can help you.

Upvotes: 1

samnu pel
samnu pel

Reputation: 914

var object = {"Key1":[1,2,3], "Key2":[4,5,6]};
var key1 = object["Key1"];
console.log(key1);

Upvotes: 2

Related Questions