Search code examples
javascriptpropertiesjavascript-objectsobject-properties

Javascript copy properties inside an object


I have an object as below;

record = {
    prop1: 'X',
    prop2: 'Y',
    prop3: 'Z'
}

Now I want all these properties to be copied to a "row" attribute inside "record". So, it should look like;

record = {
    row: {
        prop1: 'X',
        prop2: 'Y',
        prop3: 'Z'
    }
}

While I can get that using

record.row = record;

What I want is

  1. the properties prop1/prop2/prop3 to be removed as direct child of "record" after copying them inside record.row
  2. The above statement also ends up repeating the properties inside the row (sort of circular thing) which I want to avoid

How can I achieve this satisfying both the conditions ? P.S: "propX" are all simple string values, I am fine with a deep/shallow copy


Solution

  • You can do:

    let record = {
        prop1: 'X',
        prop2: 'Y',
        prop3: 'Z'
    }
    
    record = { ...record, row: record }
    

    For older version of node, you can do this instead:

    var record = {
      prop1: 'X',
      prop2: 'Y',
      prop3: 'Z'
    };
    
    
    let newRecord = {}
    Object.assign(newRecord, {
      row: record
    });
    
    // console.log(newRecord)