-1

I have an array as follows -

const options = [{text:'A', _id: '5trgh'}, {text:'B', _id: '5vjds'}, {text:'C', _id: '5njkn'}];

I want to extract the value of text based on _id. If I have just one _id, I can do it easily using filter as below -

const filteredText = options.filter(k => k._id == '5trgh'); // outputs A

I want to know what if I have multiple id's at once like 5trgh & 5vjds and I want to output A & B with filtered text.

Shobhit
  • 93
  • 7

2 Answers2

2

You can create an array and store the ids which you want to filter. Then use array filter and use includes to filter out the object whose id is in the ids array

const ids = ['5trgh', '5njkn']
const options = [{
  text: 'A',
  _id: '5trgh'
}, {
  text: 'B',
  _id: '5vjds'
}, {
  text: 'C',
  _id: '5njkn'
}];

const filterArry = options.filter(item => ids.includes(item._id));
console.log(filterArry)
brk
  • 48,835
  • 10
  • 56
  • 78
0

Do you mean this?

const options = [{text:'A', _id: '5trgh'}, {text:'B', _id: '5vjds'}, {text:'C', _id: '5njkn'}];

const IDs = options.map(item => item._id); // from this you could create buttons for example

IDs.forEach(id =>  console.log(id, options.filter(k => k._id == id)));
mplungjan
  • 169,008
  • 28
  • 173
  • 236