Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
Two forms of a copy function in javascript

There are usually two ways to copy an object. For example, using the C model, one way is you'd pass back a new object, and the second way is you'd write data to an existing object/address. Here are two ways to simulate doing that in JS:

function copy_array(arr) {
    // copy array and return existing array
    const cp = [];
    for(let i=0; i < arr.length; i++)
        cp[i] = arr[i];
    return cp;
}
function copy_to(arr, to_arr) {
    // copy to existing object
    // possible to write to a "reference object", something like `&to_arr`
    to_arr = []
    for(let i=0; i < arr.length; i++)
        to_arr[i] = arr[i];
    return to_arr;
const c = ['a','b','c'];
let arrc=copy_array(c);
const x=[];
copy_to(c, x);

Is it possible to copy objects these two ways? Or is copying to a reference object/address not possible?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

For an object you do it essentially the same way, except you use for (key in object) to iterate over the property names.

function copy_to(obj, to_obj) {
  for (let key in obj) {
    to_obj[key] = obj[key];
  }
  return to_obj;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!