Doug Cassidy
Doug Cassidy

Reputation: 1905

How to dynamically name structure elements?

xls.each(function(v, k) {
    oid = v.OrderID;        
    xlsindexed[oid] = v;//This gives me a struct with 9999 empty values.
});

I'm trying to get an array/structure with each element named as the orderID, and the value of each to be the struct with the order details.

I've tried all kinds of combinations of

xlsindexed[oid] = v;
xlsindexed.oid = v;
xlsindexed.#oid# = v;

etc

also, tried:

xlsindexed[oid] = 'blah';

and still get struct with 9999 [undefined array element]s My xls variable has about 30 elements.

Upvotes: 1

Views: 97

Answers (1)

Leigh
Leigh

Reputation: 28873

(From comments...)

This gives me a struct with 9999 empty values

Technically you get an array with that many undefined elements. The reason that happens is that when xlsindexed is undefined, CF has to guess what type of object this:

  xlsindexed[ someNumericValue ] = v; 

.. should produce: an array or a structure. Apparently, it sees the numeric value and guesses you want an array. So it creates and initializes an array with that many elements.

If you declare xlsindexed as a structure beforehand, it removes the ambiguity and produces the expected result.

// initialize as a structure
xlsindexed = {};
xls.each(function(v, k) {
    xlsindexed[v.OrderID] = v;
});

Upvotes: 1

Related Questions