skip to Main Content

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


  1. 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.

    function findNestedValue(obj, path) {
      return path.replaceAll('[', '.').replaceAll(']', '').split('.')
        .reduce((acc, curr) => acc?.[curr], obj);
    }
    const o = { 
    people: [ 
    { name: 'Alice', age: 30 }, 
    { name: 'Bob', age: 25 }, 
    { name: 'Charlie', age: 35 }, 
    ], 
    city: 'New York', 
    year: 2023, };
    console.log(findNestedValue(o, 'people[0].name'));
    console.log(findNestedValue(o, 'city'));
    Login or Signup to reply.
  2. Just use a generated function. In other cases make sure your path values aren’t 3rd party to avoid XSS attacks:

    function findNestedValue(obj, path) {
        try {
            return new Function('obj', 'return obj.' + path)(obj);
        } catch (_) {}
    }
    const o = { 
    people: [ 
    { name: 'Alice', age: 30 }, 
    { name: 'Bob', age: 25 }, 
    { name: 'Charlie', age: 35 }, 
    ], 
    city: 'New York', 
    year: 2023, };
    console.log(findNestedValue(o, 'people[0].name'));
    console.log(findNestedValue(o, 'city'));
    Login or Signup to reply.
  3. 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.

    function findNestedValue(obj, path) {
        for (const key of path.match(/[^[].]+/g)) { // anything without [].
            if (!(key in obj)) return;
            obj = obj[key];
        }
        return obj;
    }
    
    const
        object = { people: [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }, { name: 'Charlie', age: 35 }], city: 'New York', year: 2023 };
    
    console.log(findNestedValue(object, 'people[0].name')); // 'Alice'
    console.log(findNestedValue(object, 'city')); // 'New York'
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search