I have an object containing preformated attribute names of a serialized HTMLFormElement
(2-dimensional):
var plain = {
id: 1,
'items[A][Z]': 2,
'items[B]': false,
'items[C][][A]': 1
}
I want to convert the object by creating the respective sub object(s):
var result = {
id: 1,
items: {
A: {Z:2},
B: false,
C: [ {A:1} ]
}
}
As far as I'm aware, this is a common practise - but I can't find more ressources on the subject. How is something like that usually called and what's the best way to convert plain
to result
?
Edit: I've updated the examples with an Array
. This seems to be related and is also supported by the body-parser
of express.
You could split the path and reduce the path by walking the given object. If no object exist, create a new property with the name, Later assign the value and delete the splitted property.
var plain = { id: 1, 'items[A][Z]': 2, 'items[B]': false }; Object.keys(plain).forEach(function (k) { var path = k.replace(/\\[/g, '.').replace(/\\]/g, '').split('.'), last = path.pop(); if (path.length) { path.reduce(function (o, p) { return o[p] = o[p] || {}; }, plain)[last] = plain[k]; delete plain[k]; } }); console.log(plain);
ES6
var plain = { id: 1, 'items[A][Z]': 2, 'items[B]': false }; Object.keys(plain).forEach(k => { var path = k.replace(/\\[/g, '.').replace(/\\]/g, '').split('.'), last = path.pop(); if (path.length) { path.reduce((o, p) => o[p] = o[p] || {}, plain)[last] = plain[k]; delete plain[k]; } }); console.log(plain);
You could use reduce()
and filter()
like this.
var plain = { id: 1, 'items[A][Z]': 2, 'items[B]': false } var obj = {} var result = Object.keys(plain).reduce(function(r, e) { if (e.match(/\\[(.*?)\\]/gi)) { var keys = e.split(/\\[(.*?)\\]/gi).filter(e => e != ''); keys.reduce(function(a, b, i) { return (i != keys.length - 1) ? a[b] || (a[b] = {}) : a[b] = plain[e]; }, obj) } else { obj[e] = plain[e]; } return r; }, obj) console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.