How to clone objects correctly?

  • 0
    Good day! Please tell me how to properly clone any number of objects and add the id of each object by one?

    const clonObj = (obj, count) => {
      const objects = [];
    
      for (let i = 0; i < count; i++) {
        objects.push({ ...obj });
        objects[i].id = objects[i].id + 1;
      }
    
      return [...objects];
    };


    use later, something like this:
    const result = clonObj({id: 5}, 10);
    должно получиться 10 объектов и id начинаться с 5-ки

    Each obj already has a id field in advance!
    if possible, tell me how to do it correctly by adding one to each next id and not using the for loop
    JavaScript Anonymous, Nov 24, 2019

  • 3 Answers
  • 0
    There is no way without a cycle.

    const clone = (base, count, key = 'id') => [...new Array(count)].map((_, index) => {
    const cloned = { ...base };
    cloned[key] += index;

    return cloned;
    });

    const a = {
    id: 7,
    type: 'apple'
    };
    console.log(clone(a, 8));
    console.log(a);
    /**
    [
    { id: 7, type: 'apple' },
    { id: 8, type: 'apple' },
    { id: 9, type: 'apple' },
    { id: 10, type: 'apple' },
    { id: 11, type: 'apple' },
    { id: 12, type: 'apple' },
    { id: 13, type: 'apple' },
    { id: 14, type: 'apple' }
    ]
    { id: 7, type: 'apple' }
    */
    Anonymous

  • 0
    const cloneObject = (o, count = 1) => {
    const objects = new Array(count).fill(o);

    return objects.map((obj, index) => ({ ...obj, id: obj.id + index }));
    };
    Anonymous

  • 0
    instead of {... obj} use JSON.parse (JSON.stringify (obj)) , if objects are complex (their properties are also objects), but no methods or anything like https://lodash.com/docs/ 4.17.15 # cloneDeep if there are methods.

    Well, so - the use of a loop is logical here, you can just change it a little:

    for (let i = 0, id = obj.id+1; i < count; i++, id++) {
    const clone = {...JSON.parse(JSON.stringify(obj)), id}
    objects.push(clone);
    }
    Chase Melendez

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!