Reputation: 862
I have a character string
var str = 'initial.parentId=&initial.childId=431&initial.testProduit=BRU&initial.number=123';
and I would like to build the following object :
var data = {
parentId: ,
childId: 431,
testProduit: BRU,
number: 123
}
i think the best solution would be to use the split function but i can't find the best way to do it.
If you have a solution, I'm interested
Upvotes: 0
Views: 62
Reputation: 263
This will work
var str = 'initial.parentId=&initial.childId=431&initial.testProduit=BRU&initial.number=123';
let output={};
str.split("&").forEach(item=>{
let out=item.split(".").pop().split("=");
output[out[0]]=out[1];
})
console.log(output);
Upvotes: 2
Reputation: 35222
You can use URLSearchParams
to get a collection of key-value from the query string. Then loop thorough the collection and create an object
const str = 'initial.parentId=&initial.childId=431&initial.testProduit=BRU&initial.number=123',
param = new URLSearchParams(str),
output = {}
for (const [k, v] of param) {
output[k.split(".").pop()] = v
}
console.log(output)
Upvotes: 5