0

I have a simple javascript code. But it does not work as I expected. I want to extract data from javascript object but whenever I execute the function the original object array changes even though I did nothing with the original array. Is it the problem of the structure of the object array. Or async problem?

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <button onclick="test()"> </button>
</body>

<script type="text/javascript">
  var testArray = [];
var num1 = 0;
    var allorderDemo = [
    {
        name:'test1',
        orders: [
        {name: 'fanta', num:1},
        {name: 'cola', num:2},
        {name: 'sweet', num:1}
        ]
    },
    {
        name:'test2',
        orders: [
        {name: 'fanta', num:1},
        {name: 'cola', num:2},
        {name: 'sweet', num:1}
        ]
    },
    {
        name:'test3',
        orders: [
        {name: 'fanta', num:1},
        {name: 'cola', num:2},
        {name: 'ox', num:1}
        ]
    }
    ];
     function test(){
        testArray = [];
        for(var i = 0; i < allorderDemo.length; i++){
            for(var j = 0; j < allorderDemo[i].orders.length; j++){
                var index = testArray.findIndex(function(element) {
                        return (element.name == allorderDemo[i].orders[j].name);
                });
                console.log("index",index);
                if(index > 0) testArray[index].num += allorderDemo[i].orders[j].num;
                else testArray.push(allorderDemo[i].orders[j]);
            }
        }
        console.log(allorderDemo.length);
      console.log(testArray);
      console.log(allorderDemo);
    }
</script>
</html>     

I want to extract testarray from allorderdemo. But whenever I execute test function the console.log says the original array allorderdemo changes as i do not change it in the function. Why this error happens. Please help me.

Li Gang
  • 49
  • 1
  • 5

3 Answers3

0

You should change line 50 from:

else testArray.push(allorderDemo[i].orders[j]);

to:

else testArray.push({name: allorderDemo[i].orders[j].name, num:allorderDemo[i].orders[j].num});

The reason is because your code is pushing to testArray only a reference to the same object that is already inside allorderDemo . This new code I wrote will create a new object with the same data and push it into testArray.

0

The reason why this happens is that both arrays and objects are non primitive datatypes. You can read more about that here - https://medium.com/javascript-in-plain-english/javascript-reviewing-primitive-and-non-primitive-data-types-5bc4ca68c3de

In you case, you must do the below:

Replace

testArray.push(allorderDemo[i].orders[j]);`

with

testArray.push({...allorderDemo[i].orders[j]});

This way it will create a new JSON object and pushes it to the testArray. More details on the spread(...) syntax (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)

Also, you should change the index to index > -1 since the index starts from 0.

0

I think it is because of this line "testArray.push(allorderDemo[i].orders[j]"

The reason is that .orders[j] is pointing to an object e.g {name: 'fanta', num:1}, and the way that javascript passes objects is it passes the value which is a reference to the object, so when you push it into the other array, you are setting the item in testArray to point to the same object. Then when you modify the num on the testArray, you are modifying the same object that the original array points to.

See this answer for r reference about how javascript passes values: Is JavaScript a pass-by-reference or pass-by-value language?

lsdmt
  • 160
  • 1
  • 7