So in React, I have 2 arrays:
const arr1 = [
{id: 1, name: 'Hello'}
{id: 2, name: 'Dear'}
{id: 3, name: 'World'}
]
const arr2 = ['Hello', 'Dear']
I would like the arr2 values to be the id of the arr1 and end up with this:
const arr2 = [1, 2]
Thank you very much
Advertisement
Answer
Loop through arr2 and find the item with the same name in arr1. Then take the id of that item.
const arr1 = [
{id: 1, name: 'Hello'},
{id: 2, name: 'Dear'},
{id: 3, name: 'World'}
]
let arr2 = ['Hello', 'Dear']
let nameToId = arr1.reduce((result, item) => ({ ...result, [item.name]: item.id}), {});
arr2 = arr2.map((name) => nameToId[name]);
console.log(arr2);