May 15, 20206 yr I pass an array of strings to a function that turns them into an array of objects. For example array of birds names, array of dogs names. Is there any way I can check the name of the the array in that function, if it is called birds add a beak to the object, if it the dogs array add tail, for example. Thank for your help.
May 20, 20206 yr You won't be able to do what you suggested. Why not use data structures like this where it's an object with a type that can be used to deduce whether it's a list of birds or dogs and then containing some items. const birdNames = { type: 'birds', items: ['tom', 'mark'], } const dogNames = { type: 'dogs', items: ['percy', 'jack'], } const transformNames = ({ type, items }) => type === 'birds' ? items.map(name => ({ name, beak: true })) : items.map(name => ({ name, tail: true })) transformNames(birdNames) // [{ name: 'tom', beak: true }, { name: 'mark', beak: true }] transformNames(dogNames) // [{ name: 'percy', tail: true }, { name: 'jack', tail: true }] You don't want to be trying to deduce what type something is by the variable name, you should be able to rename things without worrying about breaking your app.
Create an account or sign in to comment