Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
Why split after new line is not returning single array using JavaScript?

I have a string text after fetching an API with a for loop, that returns me a list of names, each name separated by a new line. When I use the code in the snippet, it returns me each name in an individual array, instead of a single array. Is there anything wrong with the RegEx? Could someone please tell me what is wrong? Thank you very much for the help.

function loadMagicItems() {
    fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000'
    ).then(function (responses) {
        return responses.json();
    }).then(function (data) {
        displayMagicItems(data);
    });
};

function displayMagicItems(data) {
    for (let i = 0; i < data.results.length; i++) {
        const magicItemsName = data.results[i].name.split(/\n/);
        console.log(magicItemsName);
    };
};
<body onload="loadMagicItems()">
</body>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Your JSON data is an array of items. Not all items as one string seperated by a newline character.

The easiest way to get the names of the items, is to use a map and return the name of the item.

function loadMagicItems() {
  fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000').then(function(responses) {
    return responses.json();
  }).then(function(data) {
    displayMagicItems(data.results);
  });
};

function displayMagicItems(items) {
  items = items.map(({name}) => name);
  console.log(items);
};
<body onload="loadMagicItems()" />

about 4 years ago · Juan Pablo Isaza Relatório

0

Your regex is correct, this is behavior expected. For each name string you generating an array spllited by \n. If you want join the results you can do:

function displayMagicItems(data) {
    const singleArrayWithNames = []
    for (let i = 0; i < data.results.length; i++) {
        const magicItemsName = data.results[i].name.split(/\n/);
        singleArrayWithNames.push(...magicItemsName) // pushing names extracted to new array
    };
    console.log("all names: ", singleArrayWithNames)
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Since the name property is already seperated, and your'e using .split each iteration, it's creating a new array each time.

function loadMagicItems() {
    fetch('https://api.open5e.com/magicitems/?fields=slug,name,desc,type,rarity&limit=1000'
    ).then(function (responses) {
        return responses.json();
    }).then(function (data) {
        displayMagicItems(data);
    });
};

function displayMagicItems(data) {
    const magicItemsName=[]
    for (let i = 0; i < data.results.length; i++) {
        
        magicItemsName[i] = data.results[i].name;
        
    };
    console.log(magicItemsName);
};
<body onload="loadMagicItems()">
</body>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda