0

I have a usecase where I am building a js object dynamically with keys (strings) coming from outside source. How should I process the strings before using them as keys in the js object?

var strings = ["a1","2", "\@ja"]; // coming from outside source. They could be anything
var obj = {};
for(let key of strings){
    // what should do here to make sure the key string is safe to use as key
    obj[key] = "random value";
}
Teemu
  • 22,918
  • 7
  • 53
  • 106
Adam Rich
  • 86
  • 2
  • 10
  • There's no [JSON](https://www.json.org/json-en.html) in your question -> [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Dec 10 '21 at 11:49
  • Why do you think that this is a (security) problem? – Andreas Dec 10 '21 at 11:50
  • @Andreas You are right. No json involved here. I should have not added the tag. – Adam Rich Dec 10 '21 at 11:52
  • @Andreas I am thinking if any special chars or control char would be a problem when used in strings as keys – Adam Rich Dec 10 '21 at 11:53
  • Any valid string can be used as a key including `""`. – Redu Dec 10 '21 at 11:53
  • 2
    There shouldn't be any security issues with this (unless you're not going to `eval` the keys), the keys of the objects are always implictly converted to strings if a key is not a string. – Teemu Dec 10 '21 at 11:56
  • 1
    A key in an object is just a string. If there's no bug/vulnerability in the JS engine then the only problem that could arise from an unknown key is the code that uses these keys/strings. – Andreas Dec 10 '21 at 11:57
  • 1
    Althought, "_They could be anything_", if they can be live objects, then you're in troubles. Just see this [fiddle](https://jsfiddle.net/4ctf02oj/) ... But as long as the data is already in string format, there's nothing you need to do. When using that data on the server-side might need a bit inspecting. – Teemu Dec 10 '21 at 12:07
  • @Teemu Very interesting... Then maybe add `typeof key === 'string' ` as an extra check – Adam Rich Dec 10 '21 at 12:11

0 Answers0