4

I have an array (data) formatted like so:

["1", "open_order", "form", "county", "San Diego", "title_officer", "Peter", "0"]
["2", "open_order", "form", "county", "San Diego", "branch", "MV", "0"]

When I put this through a for loop and add it to the dataObject, console.log(dataObject) gives me all of the entries (this is what I want!) However, console.log(o) shows that the last entry is going into the o object for both records.

$(function() {
  var o = {};
  var dataObject = {};
  var i = 0;
  var predata = $('#preferences').text();
  var data = JSON.parse(predata);
    for(i = 0; i < data.length; i++) {
      dataObject['preferenceId'] = data[i][0];
      dataObject['pageName'] = data[i][1];
      dataObject['preferenceType'] = data[i][2];
      dataObject['baseField'] = data[i][3];
      dataObject['baseValue'] = data[i][4];
      dataObject['targetField'] = data[i][5];
      dataObject['targetValue'] = data[i][6];
      dataObject['conditionalId'] = data[i][7];
        o[i] = dataObject;
        console.log(dataObject);
    }
  console.log(o);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Any ideas why dataObject would be the same for all objects added to the o object?

1 Answer 1

6

You should init the dataObject inside the loop to make a new variable.

for(i = 0; i < data.length; i++) {
    var dataObject = {}; /* Init the variable here */
    dataObject['preferenceId'] = data[i][0];
    dataObject['pageName'] = data[i][1];
    dataObject['preferenceType'] = data[i][2];
    dataObject['baseField'] = data[i][3];
    dataObject['baseValue'] = data[i][4];
    dataObject['targetField'] = data[i][5];
    dataObject['targetValue'] = data[i][6];
    dataObject['conditionalId'] = data[i][7];
    o[i] = dataObject;
    onsole.log(dataObject);
}

This will result to:

0: {
    baseField: "county",
    baseValue: "San Diego",
    conditionalId: "0",
    pageName: "open_order",
    preferenceId: "1",
    preferenceType: "form",
    targetField: "title_officer",
    targetValue: "Peter"
}
    1: {
    baseField: "county",
    baseValue: "San Diego",
    conditionalId: "0",
    pageName: "open_order",
    preferenceId: "2",
    preferenceType: "form",
    targetField: "branch",
    targetValue: "MV",
}

The reason why all of the values on the final array is the same is that, you are just assigning the dataObject by reference and you are not making a new variable.

Sign up to request clarification or add additional context in comments.

1 Comment

Happy to help ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.