0

Having this:

array = []
array.push(111,2122,333,9)

obj.user = {
    '111'  : {},
    '2122' : {},
    '333'  : {},
    '44'   : {}
}

How can I get a new object containing only the elements that exist in the array?

In the case above, it would return:

{
    '111': {},
    '2122': {},
    '111': {}
}

I have tried this:

var newObj = _.keys(_.pick(obj.user, function(value, key) {
  if ( _.indexOf(array, parseInt(key)) != -1 ) {
    return obj.user[key]
  }
}));

Which works fine when testing on jsfiddle, but it crashes my app with process out of memory. The objects/arrays are not that large, maybe 20-30 items, but that piece of code gets executed quite a lot of times.

1 Answer 1

4

You can use _.pick:

const result = _.pick(obj.user, array);

Live Example:

const array = [];
array.push(111,2122,333,9)

const obj = {
  user: {
    '111'  : {},
    '2122' : {},
    '333'  : {},
    '44'   : {}
  }
};

const result = _.pick(obj.user, array);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

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

2 Comments

Recommend avoiding "Try this:" followed by code. Say what you've used, and ideally when it's something like _.pick, link to it (see my edit).
Running with this code for 15 minutes and so far the app didn't crash. Thanks.

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.