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

455
Visualizações
After deep copying an object in JavaScript, does the array in that object will also be converted into object?

This is my code

const assert = require('assert');
function cloneObject(obj) {
  var clone = Object.create(obj);
  for (var key in obj) {
    if (obj[key] != null && typeof obj[key] == 'object')
      clone[key] = cloneObject(obj[key]);
    else clone[key] = obj[key];
  }
  return clone;
}

var obj = {
  name: 'Vikram',
  age: 21,
  place: {
    country: 'India',
    state: 'Karnataka',
  },
  marks: [1, 2, 3, 4],
  parents: {
    father: 'Ramesh',
    mother: 'Suma',
    siblings: {
      name: 'Asha',
      age: '15',
    },
  },
};

var newObj = cloneObject(obj);
obj.parents.siblings.name = 'John';
newObj.parents.siblings.name = 'Edwin';

console.log(newObj.marks);

assert.deepEqual(Array.isArray(newObj.marks), true, 'should be an array?'); // returns actual value as false
assert(obj.parents.siblings.name === 'John');
assert(newObj.parents.siblings.name === 'Edwin');

The isArray() functions returns false , but

console.log(newObj.marks)

prints

Array { '0': 1, '1': 2, '2': 3, '3': 4 }

I know that array is also an object in JavaScript, but the isArray() function should return "True" right? The newObj.marks is now an array or object? The isArray() returns false but in console it displays "Array".

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

0

For arrays in your original object tree, the resulting objects will be non-array objects that have arrays as their prototypes, because Object.create(x) creates a non-array object with the prototype x. So yes, the result is non-array objects.

That code isn't a good implementation of deep copying, not least because it uses the original objects as prototypes for the new objects, so they remain linked. See What is the most efficient way to deep clone an object in JavaScript? for various alternatives. (Someday, you'll be able to use structuredClone — mentioned by one of those answers — but not yet.)

about 4 years ago · Juan Pablo Isaza Relatório

0

Return {false} because after cloning this return object, not an array

about 4 years ago · Juan Pablo Isaza Relatório

0

Like T.J. Crowder said there are better options.

But you could do something like:

function cloneObject(obj) {
    var clone = Object.create(obj);
    for (var key in obj) {
        if(obj[key].length && typeof (obj[key]) == "object") {
            clone[key] = [...obj[key]]
        } else if (obj[key] != null && typeof (obj[key]) == "object")
            clone[key] = cloneObject(obj[key]);
        else
            clone[key] = obj[key];
    }
    return clone;
}
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