1

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 newIndex = "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?

1 Answer 1

7

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:

Sign up to request clarification or add additional context in comments.

2 Comments

Note that in the latest edition of the standard on which JavaScript is based, it's not necessary to use bracket notation when referring to properties named by keywords or reserved words: obj.for = 'me' is permitted by ECMAScript 5th edition. (A few other contexts, such as property names in object literals, also have been loosened to permit keywords.) This change has been implemented in Firefox, for one, for a few years now, if you want to play with it.
@Jeff, yeah, forgot to mention it, in ES5 an IdentifierName can be used with the . property accessor. I'll make a better example...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.