开发者

Use the value of a string variable as the 'index' of an existing object in JavaScript

开发者 https://www.devze.com 2023-01-08 13:32 出处:网络
I am using JavaScript. I have var myobj = { "one": { "name": "paul", "no": "A123"

I am using JavaScript.

I have

var myobj = {
    "one": {
        "name": "paul",
        "no"  : "A123"
    },
    "two": {
        "name": "mike",
        "no"  : "B456"
    },
    "three": {
        "name": "andy",
        "no"  : "C789"
    },
};

I have another object newitem that I want to insert

var ne开发者_运维问答wIndex = "four";
var newItem = {
    "name": "leo",
    "no"  : "D987"
};

How do I insert newItem into myobj using newIndex as the 'index'?

By the way, newIndex is not generated by me so I cannot just say myobj.four = newItem; myobj.newIndex = newItem doesn't work since it uses the word 'newIndex' as the index instead of its value.

Any insights?


Use the bracket notation property accessor:

myobj[newIndex] = newItem;

It is also useful when you want to define a property whose name is not a valid Identifier, e.g.:

obj["1foo"] = "bar"; // `obj.1for` will cause a SyntaxError
obj["a b"] = "bar"; // `obj.a b` will cause a SyntaxError

Note that you can even use an expression with this property accessor, e.g.:

obj[someFunc()] = "foo";

It will evaluate the expression between the brackets, and it will convert the result to string, because JavaScript doesn't have true hash tables, property names must be of type String.

More info:

  • Member Operators
0

精彩评论

暂无评论...
验证码 换一张
取 消