0

I can create nested objects in Javascript like this:

var filter = {
    filterColumns: {
        value: "",
        valueText:""
        }
    };

but how can I turn filtercolumns into an array of objects? for example I would like to be able to do this:

filter.filterColumns[26].value = "value"
filter.filterColumns[26].valueText = "Bob"
filter.filterColumns[32].value = "value"
filter.filterColumns[32].valueText = "Ibb"
etc.

Thanks

EDIT: Apologies, I got this completely wrong. My original post confused javascript with C#. I have re-written it to reflect what I am trying to do.

3
  • This may provide a better description learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… Commented Jun 6, 2019 at 8:43
  • Have you seen real and working examples of C# code like that somewhere? If yes can you point us where and in what context? Or are you just asking if you can write code like that? Commented Jun 6, 2019 at 8:44
  • Sorry I'm an idiot, I meant javascript not C#! I will edit the above right away Commented Jun 6, 2019 at 8:49

1 Answer 1

2

Do you mean something like the following?

var filter = {
    filterColumns: [
        {
            value: "1",
            valueText: "Alice"
        },{
            value: "2",
            valueText: "Bob"
        },{
            value: "3",
            valueText: "Charlie"
        }
    ]
};

Now filter.filterColumns[1].valueText would contain the string "Bob";

You can for example add to the list with the following code:

filter.filterColumns.push({value: "4", valueText: "Daniel"});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes thank you. But what if I want to add a value straight to 'filter.filterColumns[32].value' without having to add a value to the first 31 elements of the array?
@NickyLarson If I'm not completely mistaken, you can simply write filter.filterColumns[32] = {value: "32", valueText: "Yoshi"}. The term you may be looking for is "sparse array".

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.