0
const test_data = [
    {
        _id: '111',
        title: 'Book',
    },
    {
        _id: '222',
        title: 'Cat,
    }
]

I have data that looks like this, and I want to use an array of titles e.g. ['Book', 'Cat'] to retrieve an array of the _ids that match with the title.

From that sample array, I want to retrieve ['111', '222'].

What I've tried was

test_data.filter((item) => { return item.title === "Book" })

But it only retrieves a single object that has Book as the title.

How can I apply this using multiple string values?

Dawn17
  • 7,825
  • 16
  • 57
  • 118

4 Answers4

1

You can use a Set for you look up table, if the value is present in the set filter the data and map it using the _id:

const test_data = [
    {
        _id: '111',
        title: 'Book',
    },
    {
        _id: '222',
        title: 'Cat',
    }
];

const filterSet = new Set(["Book", "Cat"]);

console.log(test_data.filter(({title}) => filterSet.has(title))
                     .map( ({_id}) => _id));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
0

for titles:

test_data.map(entry => entry.title);

for ids:

test_data.map(entry => entry.id);
Alex Vovchuk
  • 2,828
  • 4
  • 19
  • 40
0

You can use filter and map

const test_data = [{'_id': '111',title: 'Book',},{'_id': '222',title: 'Cat',}]
let conditions = ['Book', 'Cat']

let final = test_data
            .filter(({ title }) => conditions.includes(title))
            .map(({ _id }) => _id)

console.log(final)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

I want to use an array of titles e.g. ['Book', 'Cat'] to retrieve an array of the _ids that match with the title.

If you mean to retrieve id using the title, then the following may help you.

const test_data = [
  {
      _id: '111',
      title: 'Book',
  },
  {
      _id: '222',
      title: 'Cat',
  }
]

let new_test_data={};
for(let obj of test_data)
{
  new_test_data[obj.title]=obj._id
}

console.log(new_test_data);//{ Book: '111', Cat: '222' }
console.log(new_test_data["Book"]); //111
console.log(new_test_data["Cat"]); //111
Rohith K N
  • 845
  • 6
  • 17