0

I would like to return the parameter word of my arrow function as the property of the object key. But the object returned contains the property "word" instead.

lines = ["first row","second row","third row"]
let newLines = lines.map((item, index)=> {
                    let wordsPerLines = item.split("\s");
                    return wordsPerLines.map(word => ({ word : index}))
            }
            );
            console.log(newLines);

This is the output:

[
  [
    {
      "word": 0
    },
    {
      "word": 0
    }
  ],
  [
    {
      "word": 1
    },
    {
      "word": 1
    }
  ],
  [
    {
      "word": 2
    }
  ]
]

I would like to have instead this output :

[
  [
    {
      "first": 0
    },
    {
      "row": 0
    }
  ],
  [
    {
      "second": 1
    },
    {
      "row": 1
    }
  ],
  [
    {
      "third": 2
    },
    {
      "row": 2
    }
  ]
]
edkeveked
  • 17,989
  • 10
  • 55
  • 93
  • Though your question was closed, you have an issue with splitting strings. You are putting a regular expression in as a string. Either use `.split(' ')` or `.split(/\s/)` – chazsolo Oct 09 '17 at 18:33
  • @chazsolo, you are right, thanks! – edkeveked Oct 09 '17 at 18:48

2 Answers2

1

Javascript takes the keys in objects literally. To use a variable, change your return code to the following:

return wordsPerLines.map(word => ({ [word] : index}))

The brackets let js know it's a variable, not literally 'word'.

xavdid
  • 5,092
  • 3
  • 20
  • 32
1

You have to put the property name in square brackets:

word => ({ [word] : index})

So:

return wordsPerLines.map(word => ({ [word] : index}));

The [ ] can contain any expression. That's evaluated, and the string value of the result will be the property name.

Pointy
  • 405,095
  • 59
  • 585
  • 614