Cannot access object fields using lodash: Error cannot access objects element

Viewed 142
export default {
  configuration:
  {
    site: {
      control:[
        api: {
          'list': '/api/v1/config/sites',
          'post': '/api/v1/config/sites/',
          'patch': '/api/v1/config/sites/',
          'delete': '/api/v1/config/sites/'
        }
      ],
    },
}

I am trying to access it by _.get(configuration, ['site','control','api','list'])

2 Answers

control is an array, so you can't access control.api without first specifying which index in the array you want. Rather, you need to do:

_.get(configuration, ['site','control', '0', 'api','list'])

First thing is that your configuration structure is wrong, exactly in control:[api: {...}] the array doesn't support key/value structure like a literal object, so you should wrap that item by {} like control:[{api: {...}}] and access it like :

   _.get(configuration, ['site', 'control', '0', 'api', 'list'])

or transform your control value to an object like : control:{api: {...}}

the full example by wrapping api key by {}

let configuration = {
  site: {
    control: [{
      api: {
        'list': '/api/v1/config/sites',
        'post': '/api/v1/config/sites/',
        'patch': '/api/v1/config/sites/',
        'delete': '/api/v1/config/sites/'
      }
    }],
  }
}
var dumb = _.get(configuration, ['site','control','0','api','list'])

document.getElementById("key").innerHTML = dumb
console.log(_.get(configuration, ['site', 'control', '0', 'api', 'list']))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<p id="key"></p>

Related