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

130
Visualizações
Duplicate an item in an array basing on the sub-items attached to one of that item's keys in JavaScript

I have an array of objects that looks like this

{name:"name1", phoneNumbers:[{"home":"0700 999999"}, {"mobile":"0700 999998"}]}, {name:"name2", phoneNumbers:[{"home":"0700 999991"}, {"mobile":"0700 999995"}, fax:"48289299200"]},
{name:"name3", phoneNumbers:[{"home":"0700 999992"}, {"mobile":"0700 999988"}]}
]

What I want to achieve is something like this

{name:"name1", phoneNumbers:[{"home":"0700 999999"}]},
{name:"name1", phoneNumbers:[{"mobile":"0700 999998"}]},
{name:"name2", phoneNumbers:[{"home":"0700 999991"}]},
{name:"name2", phoneNumbers:[{"mobile":"0700 999995"}]},
{name:"name2", phoneNumbers:[{fax:"48289299200"}]},
...
]

This way, every name will be listed again with each of the contact means attached to it.

I approached this way and I found it challenging to get the solution to work since the outer loop doesn't wait for the inner loop to run exhaustively before it can continue to the next index:

const doSomeRecursion=(arr, i, result)=>{
 for(let j=0; j<arr[i]["phoneNumbers"].length; j++){                
    arr[i]["phoneNumbers"]=[arr[i]["phoneNumbers"][j]]
      result.push(arr[i])
    }
 }


const getAllContacts=(contacts)=>{

  const reconstructedContacts=[]
  for(let i=0; i<contacts.length; i++){
    doSomeRecursion(contacts, i, reconstructedContacts)
  }

  return reconstructedContacts
}

First off, this method should give me the desired result but I'm not sure why not. I also think my solution may not be the best way to go about it and I would love to know how you guys would approach this?

Edit: Thanks, @T.J. Crowder, I have corrected the question and wrapped it in a function.

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

0

The initial code block in your question has multiple syntax errors, so it's hard to be sure what your starting structure is, but making reasonable guesses at it, there's no need for recursion here at all, just nested loops:

const result = [];
for (const {name, phoneNumbers} of original) {
    for (const number of phoneNumbers) {
        result.push({name, phoneNumbers: number});
    }
}

Live Example:

const original = [
    {
        name: "name1",
        phoneNumbers: [
            { "home": "0700 999999" },
            { "mobile": "0700 999998" }
        ]
    },
    {
        name: "name2",
        phoneNumbers: [
            { "home": "0700 999991" },
            { "mobile": "0700 999995" },
            {fax: "48289299200"}
        ]
    },
    {
        name: "name3",
        phoneNumbers: [
            { "home": "0700 999992" },
            { "mobile": "0700 999988" }
        ]
    }
];

const result = [];
for (const {name, phoneNumbers} of original) {
    for (const number of phoneNumbers) {
        result.push({name, phoneNumbers: number});
    }
}

console.log(JSON.stringify(result, null, 4));

about 4 years ago · Juan Pablo Isaza Relatório

0

You could also accomplish this using a combination of flatMap() and map()

const data = [
  {name:"name1", phoneNumbers:[{"home":"0700 999999"}, {"mobile":"0700 999998"}]}, 
  {name:"name2", phoneNumbers:[{"home":"0700 999991"}, {"mobile":"0700 999995"}, 
  {"fax":"48289299200"}]},
  {name:"name3", phoneNumbers:[{"home":"0700 999992"}, {"mobile":"0700 999988"}]}
];

const result = data.flatMap((n) => {
  return n.phoneNumbers.map((pn) => {
    return { name: n.name, phoneNumbers: [pn] }
  });
});

console.log(result);

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