2

I have a nested array of objects and I'm trying to find a string inside of it. Once I find it I'd like to return the containing object. Here's my code:

const myArray = [{
    label: "Home",
    last: "odlir",
    children: [{
        label: "Home 1",
        last: "odlir1",
        children: [{
          label: "Home 2",
          last: "odlir2"
        }, {
          label: "Home 3",
          last: "odlir3"
        }]
      },
      {
        label: "Home 4",
        last: "odlir4",
        children: [{
          label: "Home 5",
          last: "odlir5"
        }, {
          label: "Home 6",
          last: "odlir6"
        }]
      }
    ]
  },
  {
    label: "dash",
    last: "gom"
  },
  {
    label: "principal",
    last: "asd"
  }
];

function contain(obj, string) {
  if (obj == null)
    return false;

  if (obj.last == string)
    return obj;

  if (typeof obj.children == 'undefined')
    return false;

  for (let i = 0; i < obj.children.length; i++) {
    if (contain(obj.children[i], string))
      return obj;
  }
  return false;
}

function getObject(array, string) {
  for (let i = 0; i < array.length; i++) {
    if (contain(array[i], string)) {
      return array[i];
    }
  }
}

console.log('test', getObject(myArray, 'odlir6'));

I'm getting back the object I want, parent object and even grandfather. Here's is a stackblitz of this code: https://stackblitz.com/edit/js-hgchmx

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Rildo Gomez
  • 305
  • 8
  • 21

1 Answers1

4

You could take a recursive approach and store the paren object for every nested call.

  1. Declare result, later this variable contains the parent object.

  2. Check if the given variable is not null but an object. Exit if not.

  3. Iterate the values from the object with a short circuit and

    • check if the value is equal to the wanted string, then return with the assignment of the object.
    • otherwise return the result of the recursive call.

function getObject(object, string) {
    var result;
    if (!object || typeof object !== 'object') return;
    Object.values(object).some(v => {
        if (v === string) return result = object;
        return result = getObject(v, string);
    });
    return result;
}

const
    array = [{ label: "Home", last: "odlir", children: [{ label: "Home 1", last: "odlir1", children: [{ label: "Home 2", last: "odlir2" }, { label: "Home 3", last: "odlir3" }] }, { label: "Home 4", last: "odlir4", children: [{ label: "Home 5", last: "odlir5" }, { label: "Home 6", last: "odlir6" }] }] }, { label: "dash", last: "gom" }, { label: "principal", last: "asd" }];

console.log(getObject(array, 'odlir6'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392