admin管理员组

文章数量:1290974

I am trying to store the following object in the browser local store via a jQuery plugin (Lawnchair):

{"key" : lcName, lcType : dataObj}

The problem I'm having is that 'lcType' is a variable (of type string) passed to the function which stores the above object, however it is not being used as the object identifier, instead the string "lcType" ends up being used.

If lcType = "Passed Object Identifier" it should look like this:

{
    "key" : "String",
    "Passed Object Identifier" : {...}
}

What I'm getting is this:

{
    "key" : "String",
    "lcType" : {...}
}

Any ideas?

I am trying to store the following object in the browser local store via a jQuery plugin (Lawnchair):

{"key" : lcName, lcType : dataObj}

The problem I'm having is that 'lcType' is a variable (of type string) passed to the function which stores the above object, however it is not being used as the object identifier, instead the string "lcType" ends up being used.

If lcType = "Passed Object Identifier" it should look like this:

{
    "key" : "String",
    "Passed Object Identifier" : {...}
}

What I'm getting is this:

{
    "key" : "String",
    "lcType" : {...}
}

Any ideas?

Share Improve this question asked Sep 4, 2011 at 21:58 dSquareddSquared 9,8355 gold badges39 silver badges54 bronze badges 2
  • 1 possible duplicate of Passing in dynamic key:value pairs to an object literal? ... this question was already asked often enough ... please use the search before you ask. – Felix Kling Commented Sep 4, 2011 at 22:05
  • @Felix Kling Thank you for pointing that out; I'll do a more thorough search next time. – dSquared Commented Sep 4, 2011 at 22:15
Add a ment  | 

2 Answers 2

Reset to default 9

Javascript objects are just associative arrays, so you can treat them as such:

var foo = { 'key' : 'some key' };
var lcType = 'foo';
foo[lcType] = 'bar';

// foo now looks like this { 'key' : 'some key', 'foo': 'bar' }
var o = {"key" : "String"};
o[lcType] = dataObj;

本文标签: jqueryUse JavaScript Variable as Object IdentifierStack Overflow