Reputation: 2551
Is it possible to set the custom index of an array with a variable.
for example:
var indexID = 5;
var temp = {
indexID: new Array()
};
The above example sets the array index to indexID
and not 5
. I have tried using =
snd quotes but I without any success.
Thnaks
Upvotes: 12
Views: 44062
Reputation: 101
var index=7; //YOUR CUSTOM INDEX
var newarray=[];
If you need array index to be an array you can do it like this:
newarray[index] = {
'KEY':'VAL',
'KEY':'VAL',
'KEY':'VAL'
}
If you need to assign just a value to your custom array index you can do it like this:
newarray[index] = "ANY-THING-YOU-WANT"
Upvotes: 0
Reputation: 3
for node-red project i had to add Apostrophe to the index name
var Trend_1={};
Trend_1[**'x'**]=Date_TimeArray;
Upvotes: 0
Reputation: 122916
You are mixing Array
with Object
. Arrays know a (numeric) index, Objects consist of key-value pairs, where key may be any string.
Not everyone would agree, bu you could extend Object.prototype
Object.prototype.append = function(key,val){
// confine to Object instances
if (this.constructor !== Object &&
!/object/i.test(this.constructor.prototype)) { return this; }
this[key] = val;
return this;
}
And subsequently use:
var temp = {}.append(indexID,[]};
Upvotes: 0
Reputation: 654
I think what you want is:
var indexID = 5;
var temp = {};
temp[indexID] = "stuff"
Upvotes: 6
Reputation: 7279
With your code, you will create an object.
Instead you can do
var indexID = 5;
var temp = [];
temp[indexID] = [];
Upvotes: 1
Reputation: 145408
Yes, just use square brackets notation:
var temp = {};
temp[indexID] = [];
Also pay attention to the fact that temp
is an object, and not an array. In JavaScript all associative arrays (or dictionaries) are represented as objects.
MORE: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId
Upvotes: 22