Home > front end >  Cloning an array of objects in JS
Cloning an array of objects in JS

Time:11-18

So I am having the following array of objects in a react app:

const ar = [{name:'name', age: 20}];

how can I multiply the ar array of objects so it has the same structure, and create like a 1000 copy of it? example:

const ar = [{name:'nameOne', age: 21},{name:'nameTwo', age: 22}]

and so on

CodePudding user response:

You can use Object.assign for the shallow copy and JSON.stringify and JSON.parse for deep copy and for 100 part you can use a loop

CodePudding user response:

If it needs to be different, you should do that with a for loop and Array.push(), like so:

for(var i = 0; i < 1000; i   ){
    ar.push({name: "name"   i, age: i   1});
}

Making it be "one, two, three" will be quite hard.

CodePudding user response:

For the shallow copy you can use the new es6 spread operator for arrays.

let arr_to_copy = [{name:'name', age: 20}];

let output_arr = [];

let i = 1000;

while (i > 0) {

  output_arr.push([...arr_to_copy])

  i--;
}

console.log(output_arr)

This won't work for deep (nested) data. Here is a good post on the spread operator

For nested data, you will have to use a lib like lodash, or make your own function.

CodePudding user response:

You could use this code to clone the array 1000 times:

const ar = [{name:'name', age: 20}];

var i = 0;
var newArray = [];

while(i < 1000){
  newArray.push(ar[0]);
  i  ;
}

console.log(newArray.length, newArray[999])
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

    const ar = [{
        name: 'nameOne',
        age: 21
    }]
    You Can use below
    for Loop
    for (let i = 0; i < 1000; i  ) {
        ar.push({
            'name': 'name'   i,
            'age': 21   i
        });
    }
  • Related