duplicate JS object using vanilla javascript

javascript copy object without reference
javascript deep copy object
javascript clone function
copy object java
javascript add object to another object
javascript object assign
lodash copy object
object.assign deep copy

I have the following response array ,I need to convert this object array to json format like the following output, So How can I convert object array to json format using pure javascript.

Below is response

var data1=[{
       vesrion:v1,
       versionData:[{
            date:'2010',
            value:123
         },{
            date:'2011',
            value:135
         },{
            date:'2012',
            value:145
         }]
      },{
       vesrion:v2,
       versionData:[{
            date:'2010',
            value:223
         },{
            date:'2011',
            value:235
         },{
            date:'2012',
            value:245
         }]
      },{
       vesrion:v3,
       versionData:[{
            date:'2010',
            value:323
         },{
            date:'2011',
            value:335
         },{
            date:'2012',
            value:345
         }]
      }]

========================================================================== required object array

[{
  date:'2010',
  data:[{
     version:v1,
     value:123
   },{
     version:v2,
     value:223
   },{
     version:v3,
     value:323
   }]
},{
   date:'2011',
  data:[{
     version:v1,
     value:135
   },{
     version:v2,
     value:235
   },{
     version:v3,
     value:335
   }]
},{
    date:'2012',
  data:[{
     version:v1,
     value:145
   },{
     version:v2,
     value:245
   },{
     version:v3,
     value:345
   }] 
}]

}

You can simply Create a map using Array.reduce() (group map by date) and Object.values() on the map will give you the desired result:

let data1=[{ vesrion:"v1", versionData:[{ date:'2010', value:123 },{ date:'2011', value:135 },{ date:'2012', value:145 }] },{ vesrion:"v2", versionData:[{ date:'2010', value:223 },{ date:'2011', value:235 },{ date:'2012', value:245 }] },{ vesrion:"v3", versionData:[{ date:'2010', value:323 },{ date:'2011', value:335 },{ date:'2012', value:345 }] }];
      
let result = Object.values(data1.reduce((a, curr)=>{
   if(curr.versionData && curr.versionData.length){
      curr.versionData.forEach((e)=>{
        a[e.date] = a[e.date] || {"date" : e.date};
        (a[e.date].data = a[e.date].data || []).push({version : curr.vesrion, value : e.value});
      });
   }
   return a;
 },{}));
 
console.log(result);

How do I correctly clone a JavaScript object?, Also, an object's prototype is referenced with the attribute __proto__ , which is also up compromising by assuming that I would only need to copy a plain Object your object, a very simple one liner is JSON.parse(JSON.stringify(object​)) :. Using the Array.filter() method. The Array.filter() method creates a new array with only elements that pass a test you include as a callback function. We can use it to remove the duplicates. On each iteration, we’ll use Array.indexOf() to see if our item already exists.

The following code will give you the same result that you want:

function a7(data1) {
 var result = [];
 var aa = {};
 var count = data1.length;
 for (var i = 0; i < count; i++) {
  var versionData = data1[i].versionData;
  if (versionData && versionData.length > 0) {
   for (var j = 0; j < versionData.length; j++) {
    var donotAdd = false;
    result.forEach(function(arrayItem) {
     if (arrayItem.date == versionData[j].date)
      donotAdd = true;
    });
    if (!donotAdd) {
     var bb = {};
     aa["date"] = versionData[j].date;
     aa["data"] = [];
     bb["version"] = data1[i].vesrion;
     bb["value"] = versionData[j].value;
     aa["data"].push(JSON.parse(JSON.stringify(bb)));
     for (var p = i; p < count; p++) {
      for (q = 0; q < data1[p].versionData.length; q++) {
       if (data1[p].versionData[q].date == aa["date"] && data1[i].vesrion != data1[p].vesrion) {
        bb = {};
        bb["version"] = data1[p].vesrion;
        bb["value"] = data1[p].versionData[q].value;
        aa["data"].push(JSON.parse(JSON.stringify(bb)));
        break;
       }
      }
      if (p == count - 1) {
       result.push(JSON.parse(JSON.stringify(aa)));
       aa = {};
      }
     }
    }
   }
  }
 }
 return result;
}

3 Ways to clone objects in JavaScript - Better Programming, Note: Be careful about using this method as your source object must be JSON safe. So it may need some sort of exception handling to keep it safe in cases in  new Set(myData.map(JSON.stringify)) creates a Set object using the stringified myData elements. Set object will ensure that every element is unique. Then I create an array based on the elements of the created set using Array.from. Finally, I use JSON.parse to convert stringified element back to an object.

You can use simple forEach for this and save data date wise in result object and get needed output by using Object.values(result) at the end.

var data = [{ vesrion:"v1", versionData:[{ date:'2010', value:123 },{ date:'2011', value:135 },{ date:'2012', value:145 }] },{ vesrion:"v2", versionData:[{ date:'2010', value:223 },{ date:'2011', value:235 },{ date:'2012', value:245 }] },{ vesrion:"v3", versionData:[{ date:'2010', value:323 },{ date:'2011', value:335 },{ date:'2012', value:345 }] }];

var result = {}

data.forEach(v1 => {
    v1.versionData.forEach(v2 => {
        result[v2.date] = result[v2.date] || {
            date: v2.date,
            data: []
        };

        result[v2.date].data.push({
            vesrion: v1.vesrion,
            value: v2.value
        });
    });
});

result = Object.values(result);

console.log(result);

Object.assign(), Removing duplicates from an array with vanilla JavaScript how a few approaches we can use to remove duplicate items from an array with vanilla JS. ES6 introduced a new object type, Set , that can be used to store data. Vanilla JS: Remove duplicates using an Object like a Set You can always try putting it into an object, and then iterating through its keys: function remove_duplicates(arr) { var obj = {}; var ret_arr = []; for (var i = 0; i < arr.length; i++) { obj[arr[i]] = true; } for (var key in obj) { ret_arr.push(key); } return ret_arr; }

A slightly longer answer that is a bit more flexible for a wider array of properties:

var sourceData=[{
    version:'v1',
    versionData:[{
        date:'2010',
        value:123
      },{
        date:'2011',
        value:135
      },{
        date:'2012',
        value:145
      }]
  },{
    version:'v2',
    versionData:[{
        date:'2010',
        value:223
      },{
        date:'2011',
        value:235
      },{
        date:'2012',
        value:245
      }]
  },{
    version:'v3',
    versionData:[{
        date:'2010',
        value:323
      },{
        date:'2011',
        value:335
      },{
        date:'2012',
        value:345
      }]
  }
];

transformData = (sourceData) => {
  const ungrouped = ungroup(sourceData, 'version', 'versionData')
  return groupBy(ungrouped, 'date', 'data')
}

ungroup = (sourceData, groupName, itemsName) => {
  const denormalized = sourceData.map( (item) => {
    group = item[groupName]
    subitems = item[itemsName]
    return subitems.map( (subitem) => ({...subitem, [groupName]: group}) )
  })
  return [].concat(...denormalized)
}

groupBy = (ungrouped, groupName, itemsName) => {
  mapped = ungrouped.reduce( (grouped, item) => {
    group = item[groupName]
    clone = { }
    for( propName in item ) {
      if(item.hasOwnProperty(propName) && propName != groupName )
        clone[propName] = item[propName]
    }
    if( !grouped.hasOwnProperty(group) ) {
      grouped[group]={[groupName]:group,[itemsName]:[]}
    }
    grouped[group][itemsName].push(clone)
    return grouped
  }, {})
  return Object.values(mapped)
}

const transformed = transformData(sourceData)
console.log(transformed)

Clone an object in vanilla JS – multiple ways, assign still doesn't copy nested objects. jQuery's $.extend() works. But that's not vanilla JS any more. What hacks do you guys use for copying JS  Duplicate a section of a form, maintaining accessibility (a11y) Using jQuery or plain JavaScript (ES6), you can now duplicate a section of a form (as well as destroy the last cloned section), the whole form, or just one or two inputs.

Removing duplicates from an array with vanilla JavaScript, My suggestion to perform deep copy is to rely on a library that's well tested, very popular and carefully maintained: Lodash. In Node.js: Here is an example that shows those two functions in use:. Basic example using Set() from ECMAScript 2015 (no library required) The Set object lets you store unique values of any type (whether primitive values or object references). If an iterable object is passed, all of its elements will be added to the new Set. Here I'll just add one value:

Best way to copy an object in JavaScript?, pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers. //if you use jQuery, you can use: In Jquery you can use: // Shallow copy Pure javascript method to deep clone object function  Copying Objects in JavaScript. Objects are the fundamental blocks of JavaScript. An object is a collection of properties, and a property is an association between a key (or name) and a value. Almost all objects in JavaScript are instances of Object which sits on the top of the prototype chain.

How to deep clone a JavaScript object, Note: Since Node.js is just a runtime built on the V8 JavaScript engine, all of It works by simply passing the object as the first argument, and the copy will be returned: and it works very well for plain objects that are easily converted to JSON. Shallow copy using … 1. The spread operator (…) is a convenient way to make a shallow copy of an array or object —when there is no nesting, it works great.

Comments
  • so you want to sort by dateinstead of versions
  • @Sau_Patil happy to help you.. please mark as accepted if it worked for you :)
  • @Sau_Patil any problem with the solution friend?
  • Thanks @Nishant Dixit