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?

0

4 Answers 4

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));

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

2 Comments

Does this keep the order?
@Dawn17 yes Array.prototype.filter will keep the order, and same for map
0

for titles:

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

for ids:

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

Comments

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)

2 Comments

Would this actually keep the order too e.g. Book matching with 111?
@Dawn17 order will depends on your test_data as we are looping on test_data to filter values
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

Comments

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.