Reputation: 1
I want store the data dynamically in java script like below format. anyone know how it will be done?
[{iKey={i3=i3Value, i2=i2Value, i1=i1Value},
sKey={s2=s2Value, s1=s1Value, s3=s3Value}}]
where i1 ,i2 ,i3,s1,s2 and s3 also dynamic values not like"i3"=xyz format.
Upvotes: 0
Views: 56
Reputation: 2671
one with not limited support.
var key = 'key1';
var value = 'value1';
//How to dynamically add key and value to a Object
var obj = {}
obj[key] = value
where i1 ,i2 ,i3,s1,s2 and s3 also dynamic values not like"i3"=xyz format.
var sampleInput = ['i1', 'i2', 'i3', 's1', 's2', 's3']
var _output = {}
for(var i=0;i<sampleInput.length;i++) {
_output[sampleInput[i]] = sampleInput[i] + "value"
}
Sample output
Object {i1: "i1value", i2: "i2value", i3: "i3value", s1: "s1value", s2: "s2value"…}
Upvotes: 1
Reputation: 21575
JavaScript objects certainly do support that, both the key and value of the object can be variables. Using the syntax {[key]: value}
For example:
var key = 'key1';
var value = 'value1';
var obj = { [key]: value }; // {key1: "value1"}
Specifically using [key]
allows you to use the value of the variable key
, rather than in the case of key: value
, where it uses the actual name key
.
Upvotes: 1