So, we are working with JSON and objects.
We did several exercises (8 ouf of 10 well done), but I’m stuck with the ninth.
The assigment says:
"Find and return the value at the given nested path in the JSON object. "
And what it give us is to start is:
function findNestedValue(obj, path) {
}
the object we are working with/on is:
var sampleJSON = {
people: [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 },
],
city: 'New York',
year: 2023, };
If I look in the test.js file (where there is the code for npm to test the results of our function), it says:
test('findNestedValue should find and return the value at the given nested path', () => { expect(findNestedValue(sampleJSON, 'people[0].name')).toBe('Alice'); expect(findNestedValue(sampleJSON, 'city')).toBe('New York'); });
Honestly, I’m lost, completely. Any tip? I’m lost, lost lost.
Any advice?
for (let key in obj) {
if (Array.isArray(obj[key])) {
for (let i = 0; i < obj[key].length; i++) {
if (obj[key][i] === path)
else {
if (obj[key] === path)
I was trying something like that, but I’m really just wandering in the dark.
3
Answers
You could first replace all square brackets, then split on
.
to get all elements of the path.Array#reduce
can be used to access each key in turn.Just use a generated function. In other cases make sure your path values aren’t 3rd party to avoid XSS attacks:
You could split the path with a regular expression which removes speparators as well.
For getting a value, you could iterate the key, check if the key exist and assign the property value to
obj
.Finally return
obj
.