-3
var car = {
  name: "roll_royce",
  add: [
    { color: "red", location: "USA_1" },
    { color: "green", location: "USA_2" },
  ],
  pay: { type: { name: "USD" } },
};

I want to write a function like this:

getCar(car, 'add.0.location') // USA_1, same as car.add[0].location 
getCar(car, 'pay.type') // USD, same as car.pay.type

But I can't use car."string". how to solve it. thanks advance ...

DecPK
  • 24,537
  • 6
  • 26
  • 42
  • Try using Lodash ~ https://lodash.com/docs/4.17.15#get – Phil Jul 18 '21 at 03:33
  • 1
    BTW, `pay.type` won't be `USD`, instead it would be `{ name: 'USD' }` – DecPK Jul 18 '21 at 03:34
  • @Phil why to use lodash when this problem can easily solved by `Array.prototype.reduce` – DecPK Jul 18 '21 at 03:35
  • 1
    @decpk that's all well and good until one of those iterations returns `undefined`. Anyway, Lodash was just a suggestion with a robust and well tested solution – Phil Jul 18 '21 at 03:37
  • 1
    @Phil very true but can handle it using `acc[curr] ?? {}` – DecPK Jul 18 '21 at 03:39

1 Answers1

0

You can use Array#reduce.

var car = {
  name: "roll_royce",
  add: [
    { color: "red", location: "USA_1" },
    { color: "green", location: "USA_2" },
  ],
  pay: { type: { name: "USD" } },
};
function getCar(obj, props){
  return props.split('.').reduce((a, b)=>a?.[b], obj);
}
console.log(getCar(car, 'add.0.location'));
console.log(getCar(car, 'pay.type'));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80