-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.

Hari_pb
  • 7,088
  • 3
  • 45
  • 53
  • 1
    does [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) not work for you? – Nina Scholz May 22 '19 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. – Hari_pb May 22 '19 at 18:33

1 Answers1

6

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)
Aziz.G
  • 3,599
  • 2
  • 17
  • 35