Wednesday 15 July 2015

javascript - Weird duplication when saving object properties to array -


I want a loop through an object, make some changes in each of its properties, and Then push them for an array. Each object property is pushed multiple times (in JSFDL, I have set it to push for simplicity twice). In each 'repetition' some properties are different (JSFDial shows only 1, i.e. 'number').

However, it seems that all objects are being pushed into a single loop and can not have exclusive properties. I am looking for a solution for this.

Sorry for my poor English, it is difficult to understand the problem and it will be easy to see JSFiddle.

Actual output:

  [{x: 1, number: 1}, {x: 1, number: 1}, {y: 2, number: 1} Expected Output:       

Pre> [{x: 1, number: 0}, {x: 1, number: 1}, {y: 2, number: 0}, {y: 2, number: 1}, {z: 3 , Number: 0}, {z: 3, number: 1}]

code:

  var item = {"a": {"x ": 1}," b ": {" y ": 2}," c ": {" z ": 3}}; Var Some = []; (For var of objects) {var item = items [key]; If (hsocproperty for the items) {for (var i = 0; i  

I will explain through dry-running. In the loop below, we choose the first thing that is "A" in your 'item' item now lets enter the loop

 for  (var of items) {// key "A" var item = objects are set to [key]; // item now refers to "objects" ["a"], which is {"x": 1} if (for the source, the property (key)) {for (var i = 0; i & lt; 2; i ++) {// Loop 1 item {"x": "1"} refers to loop 2 item, {"x": 1, "number": 0} (revised in the first iteration) ) Is mentioning the item. Number = i; // in "Loop 1", the property becomes "Number" and the object {"x": 1, "number": 0} modifies the same object in loop 2 in the / in memory. Therefore {"x": 1, "number": 0} {"x" becomes: 1, "number": 1} something. Peach (item); // is pushed into the loop 1 context of the object // is pushed into the loop 2 object of the object. // Both the reference essentially point to the same object}}}  

You will need to copy your object instead of several contexts to achieve expected output. Cloning the object in javascript is not straight forward. You can refer to this link

However, a simple solution for your current code would be to use a clone function and use it without worrying about dark cloning issues and prototype-hereditary properties. Here is the modified code.

  function clone (obz) {if (null == obj || "object"! = Typeof obj) back obj; Var copy = obj.constructor (); Copy in the obj (var etr) (if (obj.hasOwnProperty (atri)) [atri] = obj [atri];} return copy; var item = {"a": {"x": 1}, "b" : {"Y": 2}, "c": {"z": 3}} var some = []; {var of items in} {var item = items [key]; if (objects haveOwnProperty ( Key) (for (var i = 0; i & lt; 2; i ++) {var tempItem = clone (item); TempItem.number = i; some.push (tempItem);}}} Console.log (Some);  

Fast if you find it useful.


No comments:

Post a Comment