1

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?

asked Dec 18, 2017 at 9:13
3
  • It should be { items: [...items[category], item] }, and you should initialize items: - const items = { foo: [1, 2, 3] }. Commented Dec 18, 2017 at 9:16
  • 1
    I guess you want { items: [...items[category], item] } Commented Dec 18, 2017 at 9:16
  • I want to access ...items.foo via ...items.'foo', just like I can access { foo: 'bar' } by { ['foo']: 'bar' } so that I don't have to hard-code foo. Commented Dec 18, 2017 at 9:19

3 Answers 3

2

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]
answered Dec 18, 2017 at 9:50
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the same syntax:

const category = 'foo'
const items = {foo: [1, 2, 3]}
const item = 4
 
console.log({ items: [...items[category], item] })

answered Dec 18, 2017 at 9:17

Comments

0

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] });
answered Dec 18, 2017 at 10:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.