-1
var allOptions = [
    {value: 'AA', key: 'a'},
    {value: 'BB', key: 'b'},
    {value: 'CC', key: 'c'},
    {value: 'DD', key: 'd'},
    {value: 'EE', key: 'e'}
];

var selected = ['a', 'c'];

I want to get objects from allOptions which have keys in variable array selected

i.e I want result as

[
    {value: 'AA', key: 'a'},
    {value: 'CC', key: 'c'},
];

Any suggestions appreciated if not involving jquery.

2
  • 1
    does Array#filter not work for you? Commented May 22, 2019 at 18:25
  • that worked, I am new to JS and my mistake, similar questions are available, but since I can't delete question, appreciate your response. Commented May 22, 2019 at 18:33

1 Answer 1

7

You can just use includes in filter and comparing the array item with the key object.

var allOptions = [{
    value: 'AA',
    key: 'a'
  },
  {
    value: 'BB',
    key: 'b'
  },
  {
    value: 'CC',
    key: 'c'
  },
  {
    value: 'DD',
    key: 'd'
  },
  {
    value: 'EE',
    key: 'e'
  }
];

var selected = ['a', 'c'];

const res = allOptions.filter(({
  key
}) => selected.includes(key));

console.log(res)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.