0

Sorry , please bare with me , ah I would just like to ask for the terminology and how do we implement or convert a string into something like below. I am not sure if that is string array or something but the output should look like the example.

Thanks for any help and ideas. Appreciated.

let a = 'propertyAccountId';

output = "[\"propertyAccountId\"]"

let b = 'name';
output = "[\"name\"]"
MORÈ
  • 2,480
  • 3
  • 16
  • 23
Mark Latin
  • 37
  • 6
  • Your output is also a string, not an array of strings. It is probably the JSON representation of a string array but that is a different thing. – axiac Nov 28 '22 at 17:15
  • Oh I see , how do we achieve that format using javascript Sir ? if you dont mind – Mark Latin Nov 28 '22 at 17:16
  • 1
    Indeed, JSON of an array containing the string. `JSON.stringify([b])` should do it. – Amadan Nov 28 '22 at 17:17
  • 1
    Create an [array](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays) that contains only the input string then produce its JSON representation using [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). – axiac Nov 28 '22 at 17:18
  • Does this answer your question? [Convert array to JSON](https://stackoverflow.com/questions/2295496/convert-array-to-json) – 0stone0 Nov 28 '22 at 17:20
  • Does this answer your question? [Escaping double quotes with back slash](https://stackoverflow.com/questions/59678213/escaping-double-quotes-with-back-slash) – 0stone0 Nov 28 '22 at 17:26

3 Answers3

1

For get the output you desire you could do this:

const b = 'name'
const output = JSON.stringify([b])
Martinez
  • 1,109
  • 1
  • 4
  • 13
0
let a = "propertyAccountId";

function convert(stringvar){
   var newstring = `["${stringvar}"]`
   return newstring;
}

console.log(convert(a));

See desired output in console here:

https://codesandbox.io/s/floral-leaf-ioxb26?file=/src/index.js:0-143

Hope this helped.

Happy coding :)

Mr.Code77
  • 3
  • 3
-2

You can turn your string input to your requested string output like below:

let a = 'propertyAccountId';
let b = 'name';
const convert = input => {
  return JSON.stringify([input])
}

console.log(convert(a))
console.log(convert(b))

Edit

Removed unnecessary replace function

jjj
  • 378
  • 1
  • 6
  • This converts into the required string format with escaped double quote – jjj Nov 28 '22 at 17:29
  • Don't confuse the value of a variable as data (`["name"]`) with its representation as JSON or as JavaScript code. There is no backslash in the data, it exists only in the source code and in the JSON representation because in these representations the quote character (`"`) has a special meaning and it needs to be escaped to represent itself. – axiac Nov 28 '22 at 17:48