So, we are working with data-objects parsed from JSON-strings.
We did several exercises (8 out of 10 well done), but I'm stuck with the ninth.
The assignment says:
Find and return the value at the given nested path in the
JSON[data]-object.
And what it gives us is to start with:
function findNestedValue(obj, path) {
}
The object we are working with/on is:
const sampleDate = {
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(sampleData, 'people[0].name')).toBe('Alice');
expect(findNestedValue(sampleData, '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.
You could first replace all square brackets, then split on
.to get all elements of the path.Array#reducecan be used to access each key in turn.