1

I have a SelectList from my C# Controller method that contains 8 text/value pairs. I would like to convert this to a JavaScript array that I can access in a foreignKey column of a kendo grid. The structure of my arObjArray is ok as expected. The only problem is the content of the array is wrong. Instead of having a list of 8 pairs consistent with the packageList item, I get an array of 8 rows with each row having the same value as the very last item in packageList. The relevant section of my javascript function is like this:

var arObjArray = []; var arObj = {}; @foreach (SelectListItem d in packageList) { @:arObj["text"] = "@d.Text"; @:arObj["value"] = Number("@d.Value"); @:arObjArray.push(arObj); } console.log(arObjArray) 

What am I missing here?

2
  • 2
    JavaScript will pass objects by reference - instead of declaring arObj outside the loop, declare it inside, or just push an object directly from inside the loop. @:arObjArray.push({text: "", value: ""})
    – tymeJV
    CommentedJan 13, 2020 at 21:41
  • 2
    You should use JSON.
    – SLaks
    CommentedJan 13, 2020 at 21:42

1 Answer 1

2

Objects are passed by reference, the same as instances in C#. In your foreach loop you are actually reusing the same object over and over, because it is only assigned to an empty object once (var arObj = {}; outside the loop). Thus you're pushing one object to the array multiple times, and modifying the values of that one object each array iteration.

Declare and assign arObj inside the loop instead:

@foreach (SelectListItem d in packageList) { var arObj = {}; @:arObj["text"] = "@d.Text"; @:arObj["value"] = Number("@d.Value"); @:arObjArray.push(arObj); } 
1
  • tymeJV's suggestion did it. Not sure which Internet post I got the @foreach, @:arObj from.CommentedJan 14, 2020 at 0:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.