felixRo felixRo - 1 year ago 70
Javascript Question

how to convert string build from variables to an object

I have something like this:

val = val.split(".");
//val[0] is name
//val[1] is John

I have to build object like this:

{name: "John"}

So I do:

filterArray = "'{'"+val[0]+"':'"+val[1]+"'}'";

var t = JSON.parse(filterArray);

And when I do

I want to get: Object { name: "John" }

But can't do it the right why, please help :)

Answer Source

This is how that should be done

val = val.split(".");
// Declaring an empty object
obj = {};
// Assingning a dynamic key and its value form you variable
obj[val[0]] = val[1];
console.log(obj) // Object { name: "John" }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download