Getpathvalue() Function For Deep Objects With Arrays And With Packed Json
For background, please refer to this question: Access deep object member of embeded JSON The solutions offered there worked very well with the packed JSON contained in key values.
Solution 1:
You could replace the brackets and take the remaining values as keys. Inside of the reducing, you could use a default object for not given objects.
functiongetValue(object, path) {
return path
.replace(/\[/g, '.')
.replace(/\]/g, '')
.split('.')
.reduce(function (o, k) {
return (typeof o === 'string' ? JSON.parse(o) : (o || {}))[k];
}, object);
}
var object = {"id":"0001","type":"donut","name":"Cake","ppu":0.55,"batters":{"batter":[{"id":"1001","type":"Regular"},{"id":"1002","type":"Chocolate"}]},"data":"{\"domain\":\"cooking.com\",\"id\":53819390}"},
path = 'batters.batter[1].id';
console.log(getValue(object, path));
Solution 2:
The following would do the job using a Regex on each value :
const data = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
}
]
},
"data": "{\"domain\":\"cooking.com\",\"id\":53819390}"
}
functiongetValue(object, path) {
return path
.split('.')
.reduce(function (o, k) {
const indexSearch = (newRegExp(/\[([0-9]*)\]/)).exec(k)
const index = indexSearch ? indexSearch[1] : null
k = k.replace(/\[[0-9]*\]/, '')
const sub = (typeof o === 'string' ? JSON.parse(o) : o)[k]
return index ? sub[index] : sub;
}, object);
}
console.log(getValue(data, 'batters.batter[1]'))
console.log(getValue(data, 'data.domain'))
console.log(getValue(data, 'batters.batter[1].id'))
Post a Comment for "Getpathvalue() Function For Deep Objects With Arrays And With Packed Json"