How to export and import object array in Javascript?

Asked

Viewed 973 times

1

I am creating a system, and within the main codes I have large arrays of objects that store information about products and information in which I use within the functions for certain system operations.

However, storing the product information on the main code page is bothering me a lot and I would like to know if there is any way to import these object arrays from one page to another without compromising the functionalities of the functions they use as a parameter some product information.

Code example:

const produtos = [
    {nome: "notebook", custo: 1.500},
    {nome: "cama", custo: 2000},
    {nome: "ventilador", custo: 200}
]

function getNames(){

    produtos.map((produto) => {
        return produto.nome
    })
}

In this example, I would like to put the object array on another page, to make an import without compromising the function getNames(). Would that be possible?

  • Maybe load from a JSON file using Xios?

  • and how I would do that?

  • you are only using vanilla javascript (html javascript)?

  • I am using JS NODE and React JS

2 answers

3

Only export the Function

the file where the function is located

export const getNames = () => produtos.map(({ name }) => name)

the file where you want to use the function

import { getNames } from './path/to/file'

I hope it helped

  • Vish vey, tried and gave the following error: Parsing error: 'import' and 'export' may only appear at the top level

1


The easiest way to import to Node is by using the function require(path), exporting the object through the attribute module.exports, thus as follows:

Archive that exports:

// Atribui a module.exports o objeto para ser exportado

const produtos = [
    {nome: "notebook", custo: 1.500},
    {nome: "cama", custo: 2000},
    {nome: "ventilador", custo: 200}
]

module.exports = produtos;

// Você também pode importar vários objetos colocando-os dentro de um objeto.
// Exemplo: module.exports = {produtos: produtos, registro: "2020-03-12", code: 3714};

File that matters:

const produtos = require("./path/arquivo_que_exporta");

One interesting thing, is that the entire script runs before the object is exported. See the example below:

module.exports = [1, 2, 3];

// Essa mensagem será impressa antes do objeto ser exportado no outro arquivo.
console.log("Continua a execução...");
  • and how I would export more than one object array at the same time?

  • You must place the objects inside an object. I edited the answer for you to better understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.