0

I have seen this in javascript but have no idea what it does. can someone explain? and before you say "google it". I have tried and I cannot see any results for it

return {
    [API]: {
        data: { someData },
        anotherKey: true,
}

I know API is a string from the code I'm looking at but I'm not sure what this is doing

I'm used to just seeing an object returned like this.

return {
   key: value
}

can someone please enlighten me? happy to read docs/videos etc. just honestly not sure what to google to find them

The Decimator
  • 71
  • 1
  • 7
  • 3
    Does this help? https://stackoverflow.com/questions/6500573/dynamic-keys-for-object-literals-in-javascript Possibly a duplicate? Particularly the *"Computed property names"* answers. – Kevin B Nov 12 '18 at 20:20
  • 3
    Specifically, this: https://stackoverflow.com/a/38774377/1822698 – slider Nov 12 '18 at 20:21
  • @KevinB I'm sure there's a dup but that one looks a little old; this question is specifically about computed property names in an object initializer. – Pointy Nov 12 '18 at 20:21
  • 2
    Agreed, why i'm hesitant to hammer it – Kevin B Nov 12 '18 at 20:22
  • @slider ah good, cool – Pointy Nov 12 '18 at 20:22
  • 3
    They are computed property names https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names – lemieuxster Nov 12 '18 at 20:22
  • don't hammer me folks, I have been given my answer now. the tech world moves forward – The Decimator Nov 12 '18 at 20:24
  • I had no idea this existed. Thanks for asking the question and everyone else for answering it. – Will Nov 12 '18 at 20:25
  • 2
    @TheDecimator Sorry that was just SO lingo, hammer means close as duplicate. That makes this post essentially a sign post to another Q&A pair that already has a good answer to this question. It's referred to as a "hammer" when it is done by someone with a gold tag badge, because it can be done with a single vote by such users. Not a bad thing. – Kevin B Nov 12 '18 at 20:28

3 Answers3

4

These are known as Computed Property Names. Hopefully this example illustrates it's mechnanism and usefulness

let pet = 'cat';
let person1 = {name: "Dave", [pet]: "Muffin"};

pet = 'dog';
let person2 = {name: "Mary", [pet]: "Fido"};


console.log(person1,person2);
Olian04
  • 6,480
  • 2
  • 27
  • 54
code_monk
  • 9,451
  • 2
  • 42
  • 41
0

If API is a string, let's say "apiObject" then you have

return 
    {
    apiObject: {
        data: { someData },
        anotherKey: true,
    }
eag845
  • 1,013
  • 1
  • 11
  • 16
-3

I think the [API] return format is for an "object", the second is simply a return "value". I may be wrong, that's just my first guess.

Brian biggs
  • 27
  • 1
  • 6