With objects, I can wrap a key in square brackets like so:
// A.js
const category = 'foo'
return { [category] : 'bar' } // { foo: 'bar' }
Is there an easy way to do the same with array elements? Like
// B.js
const category = 'foo'
const items.foo = [1, 2, 3]
const item = 4
return { items: [...items.category, item] } // throws an error
I'd like to be able to get {items: [1, 2, 3, 4]} in B.js
Is there a way?
3 Answers 3
Both the dot notation and square brackets are property accessors.
If you use the dot notation, the property must be the actual property name:
words=new Object;
words.greeting='hello';
console.log(words.greeting); //hello
console.log(words['greeting']); //hello
console.log(words[greeting]); //error
In the third example, greeting is treated as a variable, not as a string literal, and because greeting has not been defined as a variable, the JavaScript interpreter throws an error.
If we define greeting as a variable:
var greeting = 'greeting';
the third example works:
words=new Object;
words.greeting='hello';
var greeting='greeting';
console.log(words[greeting]);
So you need to use square brackets as the property accessor:
[...items[category],item]
Comments
You can use the same syntax:
const category = 'foo'
const items = {foo: [1, 2, 3]}
const item = 4
console.log({ items: [...items[category], item] })
Comments
If you want to access the foo property using another variable, you can just use square brackets notation, like so:
const category = 'foo'
const items = {
foo: [1, 2, 3]
}
const item = 4
console.log( { items: [...items[category], item] });
{ items: [...items[category], item] }, and you should initialize items: -const items = { foo: [1, 2, 3] }.{ items: [...items[category], item] }