0

MyIds has just two Id numbers 1 and 2

var MyIds = [1,2]

but MyObject has three Id numbers 1, 2 and 3 (In reality this has about 500 Id's)

var MyObject = [{id:1,size:21,length:31},{id:2,size:22,length:32},{id:3,size:23,length:33}]

and I want to make a new variable that looks like this, I need some magic code that will compare the two variables and only return the details of the objects where the Is's match

var Result = [{id:1,size:21,length:31},{id:2,size:22,length:32}]

I'm happy to use jQuery if it help

4 Answers 4

2

Use Array.prototype.filter()

var Result = MyObject.filter(function(item){
  return MyIds.indexOf(item.id) >-1;
});
Sign up to request clarification or add additional context in comments.

Comments

0

It can be easily solved with underscore or lodash with something like:

Result = _.filter(MyObject, function (item) {
    return _.indexOf(item.id, MyIds) !== -1;
});

I admit, this is a lazy answer. There is probably a way to make it without adding a news library. But lodash is so cool :)

Comments

0

It can be done without jQuery:

var MyIds = [1,2];
var MyObject = [{id:1,size:21,length:31},{id:2,size:22,length:32},{id:3,size:23,length:33}];

var Result = [];

MyObject.forEach(function(element) {
    MyIds.forEach(function(id){
      if(element.id == id)
        Result.push(element);
    });
});

Comments

0

A more diverse sollution without using any library:

  function find(propName, filters, collection){
    var temp = [];
    for(var i = 0; i < collection.length; i++){
        for(var j = 0; j < filters.length; j++){
            if(collection[i][propName] === filters[j]){
                temp.push(collection[i]);   
                break;
            }
        }
    }
    return temp;

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.