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

243
Visualizações
How to make an array of objects from an array of elements

This is driving me crazy.

I have an array like so:

myArray = ['A', 'B', 'C', 'D', 'E', 'F', ];

and my code is making a NEW object that will look like this:

myNewObj = [
 {
   name: "A",
   displayName: "A"
 },
 {
   name: "B",
   displayName: "B"
 },
 {
   name: "C",
   displayName: "C"
 },
 {
   name: "C",
   displayName: "C"
 },
 {
   name: "D",
   displayName: "D"
 },
 {
   name: "E",
   displayName: "E"
 },
 {
   name: "F",
   displayName: "F"
 }
]

My code gets values in the myArray and I want to create myNewObj

This is how I'm doing it so far

I create the new object

let newObj = [{
    "name": "",
    "displayName": ""
}];

Then I use a simple FOR NEXT loop and it work up until a point and claims newObj[i].name IS UNDEFINED... how is that possible when I'm defining it and see it in the Google dev console?

            for (let i = 0; i < myArray.length; i++) {
                newObj[i].name = myArray[i];
                newObj[i].displayName = myArray[i];

                myNewObj.push(newObj);
            }

However, I consistently get this error:

newObj[i].name is NOT DEFINED and it dies.

UPDATE: Everything's working and here's the ACTUAL real data

But as you can see, the prototype is there and when I save to sessionStorage, I get [Object,Object], x 12....

enter image description here

do I need to strip out name: and displayName: and put into yet another object?

enter image description here

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

0

Using Array#map:

const myArray = ['A', 'B', 'C', 'D', 'E', 'F'];

const myNewArray = myArray.map(e => ({ name: e, displayName: e }));

console.log(myNewArray);

Your solution (you need to initialize the array as [] and create a new object in every iteration to push it):

const myArray = ['A', 'B', 'C', 'D', 'E', 'F'];

const myNewArray = [];

for (let i = 0; i < myArray.length; i++) {
  const obj = {};
  obj.name = myArray[i];
  obj.displayName = myArray[i];
  myNewArray.push(obj);
}

console.log(myNewArray);

about 4 years ago · Juan Pablo Isaza Relatório

0

Issue with the code

You are doing the Array.Push incorrectly. Your let newObj should be an object, not an array. It should be initialized inside the loop. so that each execution takes a different memory location. You should define myNewObj as an empty array and should push your newObj into myNewObj array inside the loop.

Working Fiddle

const myArray = ['A', 'B', 'C', 'D', 'E', 'F'];
const myNewObj = [];
for (let i = 0; i < myArray.length; i++) {
  let newObj = {
    "name": "",
    "displayName": ""
  };
  newObj.name = myArray[i];
  newObj.displayName = myArray[i];
  myNewObj.push(newObj);
};
console.log(myNewObj);

Better Approach

A better approach for this issue is to use Array.map. Array.map returns a new array from an existing array. You could run Array.map on myArray and construct myNewObj array as below.

Working Fiddle

const myArray = ['A', 'B', 'C', 'D', 'E', 'F'];
const myNewObj = myArray.map((item) => ({ name: item, dispayName: item}));
console.log(myNewObj)

about 4 years ago · Juan Pablo Isaza Relatório

0

var myArray = ['A', 'B', 'C', 'D', 'E', 'F', ];
var myNewObj = [];
for (let i = 0; i < myArray.length; i++) {
            var newObj = {
            name:'',
            displayName:''
            };
                newObj['name'] = myArray[i];
                newObj['displayName'] = myArray[i];

                myNewObj.push(newObj);
}
console.log(myNewObj);

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