0

I have an array with some existing fields and I need to add a few new fields in that array, below is working

myArray.myNewField1 = "someValue";

but I need that field's name should have spaces in between them or some special characters like space or #$% and so and I tried below and it showing some syntax error;

myArray.["myNew Field #1"] = "someValue";

Is it allowed to create any attributes names with special characters in Javascript?

2
  • 1
    Just remove the dot, it's as simple as myArray["myNew Field #1"] Commented Dec 11, 2019 at 13:42
  • As stated in one of the answers, this is an object not an array... don't get them confused as they're entirely different things Commented Dec 11, 2019 at 13:45

3 Answers 3

2

Yes you can, but in Objects, not arrays, just remove the . before the bracket :

const myObj = {};

myObj["myNew Field #1"] = "someValue";

console.log(myObj);

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

1 Comment

I know the OP had myArray as the variable name, but I'd suggest changing it in your example to remove further confusion (especially as you do point out it's an object)
0

Just remove the .:

myArray["myNew Field #1"] = "someValue";

Comments

0

Try this:

myArray["myNew Field #1"] = "someValue";

Comments

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.