I have a data structure like this :
var someObject = {
'part1' : {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'part2' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'part3' : [
{
'name': 'Part 3A',
'size': '10',
'qty' : '20'
}, {
'name': 'Part 3B',
'size': '5',
'qty' : '20'
}, {
'name': 'Part 3C',
'size': '7.5',
'qty' : '20'
}
]
};
And I would like to access the data using these variable :
var part1name = "part1.name";
var part2quantity = "part2.qty";
var part3name1 = "part3[0].name";
part1name should be filled with someObject.part1.name
's value, which is "Part 1". Same thing with part2quantity which filled with 60.
Is there anyway to achieve this with either pure javascript or JQuery?
The solutions here are just for accessing the deeply nested keys. I needed one for accessing, adding, modifying and deleting the keys. This is what I came up with:
path_to_key
: path in an array. You can replace it by yourstring_path.split(".")
.type_of_function
: 0 for accessing(dont pass any value tovalue
), 0 for add and modify. 1 for delete.This is the solution I use:
Example usage:
Limitations:
[]
) for array indices—though specifying array indices between the separator token (e.g.,.
) works fine as shown above.While reduce is good, I am surprised no one used forEach:
Test
Inspired by @webjay's answer: https://stackoverflow.com/a/46008856/4110122
I made this function which can you use it to Get/ Set/ Unset any value in object
To use it:
If you need to access different nested key without knowing it at coding time (it will be trivial to address them) you can use the array notation accessor:
They are equivalent to the dot notation accessor and may vary at runtime, for example:
is equivalent to
or
I hope this address your question...
EDIT
I won't use a string to mantain a sort of xpath query to access an object value. As you have to call a function to parse the query and retrieve the value I would follow another path (not :
or, if you are uneasy with the apply method
The functions are shorter, clearer, the interpreter check them for you for syntax errors and so on.
By the way, I feel that a simple assignment made at right time will be sufficent...
Building off of Alnitak's answer:
}
This allows you to set a value as well!
I've created an npm package and github with this as well