0

I am trying to do something like this;

var fieldName = 'name';
if ((await db.friends.where({ ${fieldName}: 'Josephine'}).count()) === 0) {
        const id = await db.friends.add({name: "Josephine", age: 21});
        alert (`Addded friend with id ${id}`);
    }

Is the any way to do this thing in Javascript? Thanks

R0bertinski
  • 517
  • 6
  • 12

1 Answers1

2

Yes, but you have to use []:

var fieldName = 'name';
if ((await db.friends.where({ [fieldName]: 'Josephine'}).count()) === 0) {
    const id = await db.friends.add({name: "Josephine", age: 21});
    alert (`Addded friend with id ${id}`);
}
Marian Theisen
  • 6,100
  • 29
  • 39
  • (I dont know the use case and background, BUT be aware of SQL injection possibilities if you do stuff like this. If you can, use an allow-list for the fieldNames - if your ORM does not prevent this automatically) – Marian Theisen Mar 25 '21 at 06:46