0

I have this code with array:

const dataToset = [
    { key: 'key1', value: "some data" },
    { key: 'key2', value: 37 },
];

await db.query(`
    UPDATE some_table 
    SET ${dataToset.map(data => `${data.key} = ${data.value}`)}
    WHERE id ${id}`);

result query is next: UPDATE some_table SET key1=some data,key2=37 WHERE id=1 and it fails, because some data should be passed as string. How to get valid query: UPDATE some_table SET key1="some data",key2=37 WHERE id=1?

p.s. I am getting next error: syntax error near "data"

2
  • Isn't it WHERE id=1? Commented May 29, 2020 at 6:49
  • nope, fixed it here. Commented May 29, 2020 at 7:01

1 Answer 1

1

Aside from syntax error (it has to be WHERE id=1), I would do explicit array to string conversion, using .join(', ') and somewhat change your template string, paying attention that (only) string value should be enclosed into single quotes:

const dataToset = [
          { key: 'key1', value: "some data" },
          { key: 'key2', value: 37 },
      ],
      id = 1
      query = `
        UPDATE some_table
        SET ${
          dataToset
            .map(({key,value}) => 
              typeof value == 'string' ? 
              key+"='"+value+"'" : 
              key+'='+value)
            .join(', ')
        }
        WHERE id=${id}
      `

console.log(query)
.as-console-wrapper{min-height:100%;}

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

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.