2

I have an object like

let arr = [
  {
    title: "hello",
    pivot: {
      id: 1,
      bid: 3
    }
  },
  {
    title: "home",
    pivot: {
      id: 2,
      bid: 3
    }
  },
  {
    title: "nice",
    pivot: {
      id: 3,
      bid: 3
    }
  }
];

I want to access its property dynamically. I want to access id property's value from pivot from first object of this array. And it's should be dynamic.

This is what I tried already.

let s = "0.pivot.id"
let res = arr[s]
console.log(res)

I can access by arr[0].pivot.id but this is not my case. I want it dynamically.

Anwarul Islam
  • 561
  • 7
  • 29
  • Why? All items have a `pivot` and all `pivot`'s have an `id`. So accessing those with hardcoded dot notation makes the most sense. – Alex Wayne Jan 27 '20 at 18:44
  • 1
    Or something like this: [`_.get`](https://lodash.com/docs/#get). You can't pass a full path, you have to derefernce each level. – zero298 Jan 27 '20 at 18:44

2 Answers2

2

what you tried would give you a property which key was 0.pivot.id. So it might work if your object looks like this

{ 
    '0.pivot.id': 'something'
}

There is no native way to access deeper level of an object dynamically. You would need to use recursion for that.

It's quite easy though, You could simply split your key into an array of keys and then recursively check your array for matching keys.

let arr = [
  {
    title: "hello",
    pivot: {
      id: 1,
      bid: 3
    }
  },
  {
    title: "home",
    pivot: {
      id: 2,
      bid: 3
    }
  },
  {
    title: "nice",
    pivot: {
      id: 3,
      bid: 3
    }
  }
];

function getDynamicKeyRecursively(object, key) {
  // the key needs to be an array, 
  // if it isn't, we split it into an array
  if(typeof key === 'string') {
      key = key.split('.');
  }
  // we get the current value of the current object
  let currentValue = object[key[0]];
  // remove the first index of the key
  key.shift()
  // if the current value is an object or an array, we recursively check this value for what we want
  // otherwise, we return the value.
  return Array.isArray(currentValue) || typeof currentValue === 'object' ? getDynamicKeyRecursively(currentValue, key) : currentValue;
}

console.log(getDynamicKeyRecursively(arr, '1.pivot.id'));
Nicolas
  • 8,077
  • 4
  • 21
  • 51
2

You can split the string and loop through it updating a variable refrencing the last found value :

let arr = [
  {
    title: "hello",
    pivot: {
      id: 1,
      bid: 3
    }
  },
  {
    title: "home",
    pivot: {
      id: 2,
      bid: 3
    }
  },
  {
    title: "nice",
    pivot: {
      id: 3,
      bid: 3
    }
  }
];

let s = "0.pivot.id";

const getValue = (arr, str) => {
  let ref = arr;
  const keys = str.split(".");

  keys.forEach(k => {
    ref = ref[k];
  });

  return ref;
};

const result = getValue(arr, s);

console.log(result);
Taki
  • 17,320
  • 4
  • 26
  • 47