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

176
Visualizações
Creating new array of objects from specific values in 2 different arrays (JavaScript)

I got these 2 arrays:

const data = [
  { url: 'google.com', title: 'google', social: false, corporate: true },
  { url: 'facebook.com', title: 'facebook', social: true, corporate: true }
 ];

const valuesToExtract = ['url', 'title'];

I need to get to this result:

const result = [
 { url: 'somepath[0].url', title: 'somepath[0].title' },
 { url: 'somepath[1].url', title: 'somepath[1].title' }
]

I tried this way:

const newArray = [];    
for (let i = 0; i < data.length; i++) {
  for (const value of valuesToExtract ) {
    const newObject = {};
      newObject[value] = `somepath[${i}].${value}`;
      newArray.push(newObject);
  }
}

But the result I get is:

const result = [
  { url: 'somepath[0].url' },
  { title: 'somepath[0].title' },
  { url: 'somepath[1].url' },
  { title: 'somepath[1].title' }
]

How can I do it better?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Just need to change a bit of where to put stuff in your nested loops. You need two loops:

  1. The first loop goes over the data array
  2. For every data point, the 2nd loop goes over the valuesToExtract

Therefore, you only want to push your newObject once the 2nd loop has finished (meaning once valuesToExtract has finished extracting). This way, you get a newObject for every data item.

const data = [
  { url: 'google.com', title: 'google', social: false, corporate: true },
  { url: 'facebook.com', title: 'facebook', social: true, corporate: true }
 ];

const valuesToExtract = ['url', 'title'];
const newArray = [];    
for (let i = 0; i < data.length; i++) {
  // Create a new Object for every data item
  const newObject = {};
  for (const value of valuesToExtract ) {
      newObject[value] = `somepath[${i}].${value}`;
  }
  newArray.push(newObject);
}

console.log(newArray)

about 4 years ago · Santiago Gelvez 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