felixRo felixRo - 23 days ago 8
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
console.log(filterArray);


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

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

Answer

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" }