Nithyashree B L
Nithyashree B L

Reputation: 99

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".

Upvotes: 0

Views: 44

Answers (3)

S.Visser
S.Visser

Reputation: 4725

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;
}

Upvotes: 0

Kyrylo Ovsiannik
Kyrylo Ovsiannik

Reputation: 13

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

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.)

Upvotes: 2

Related Questions