0

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]}
1
  • If you have var myObject = {"Key1":[obj1,obj2,obj3], "Key2":[obj4,obj5,obj6]}; shouldn't it just be myObject['Key1']? Commented Nov 21, 2017 at 20:19

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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)

Comments

0

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]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.