Chipe Chipe - 22 days ago 6
Javascript Question

Importing an object that is inside of the exported object JavaScript

I am exporting an object to be imported into other modules. In other modules I dont need the full object but other objects inside of that exported object. How can I drill down to the specific object inside of the exported object?

exported JS:

const data = {
someObject:{//...},
anotherObject:{//...}
}

export default data;


importing into another file:

import data from './dataModule'


data
here is that full object from
dataModule
but I want to get only
someObject
inside of the full object. How can I drill down to importing only that object?

import data.someObject from './dataModule'
does not seem to work

Answer

You can use object deconstruction which looks something like this:

const obj = {
  name: 'Tim',
  location: {
    lat: 123,
    lng: 321
  }
}

const {name} = obj
const {location: {lat,lng}} = obj

And if we want to get it from import, it looks like this:

import {name} from './fileWithObj'

with an export of so:

const obj = {
      name: 'Tim',
      location: {
        lat: 123,
        lng: 321
      }
    }
export default obj