Reputation: 71
I have to convert,
string1 : "test1.$.test2",
into
test1:[{
test2:"{value will be assign later in the code}"
}]
I have de structured the string into test1 and test2 using split function, which gives me
How do I construct the above format from string? or is there any function in lodash or any npm package I can use?
Upvotes: 0
Views: 58
Reputation: 63524
You can match
on test
followed by a number to return an array of matches, and then use computed property names to build the data structure.
const str = 'test1.$.test2';
const [ first, second ] = str.match(/test\d/g);
const data = {
[first]: [
{ [second]: '' }
]
};
console.log(data);
Additional documentation
Upvotes: 1
Reputation: 3635
You can use { [myFieldVariable]: value }
notation as follows:
myInput = "test1.$.test2"
fields = myInput.split('.$.'); // ['test1', 'test2']
myObject = {
[fields[0]]: [ { [fields[1]]: "value assigned later" } ]
};
Now doing console.log(JSON.stringify(myObject, null, ' '))
shows that the object is in the structure you want.
{
"test1": [
{
"test2": "value assigned later"
}
]
}
Upvotes: 2