1

I want to use the number from another object as my object key

I tried using ${} while making the object(resulting in parsing error)

{
    this.props.tasks.map(i=>{
        return (
            data.push({
                name:i.name,
                `${parseInt(i.start, 10)}`:'x',
                `${parseInt(i.end, 10)}`:'x'
            })
        );
    })
}

error message:

Line 30:21:  Parsing error: Unexpected token

  28 |                 data.push({
  29 |                     name:i.name,
> 30 |                     `${parseInt(i.start, 10)}`:'x',
     |                     ^
  31 |                     `${parseInt(i.end, 10)}`:'x'   
  32 |                 })
  33 |                 );
Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
  • Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names – sibasishm Oct 22 '19 at 06:19

2 Answers2

2

You can use computed property names

{
  this.props.tasks
    .map(i => {
      return (data.push({ 
        name: i.name,
        [`${parseInt(i.start, 10)}`]: 'x',
        [`${parseInt(i.end, 10)}`]: 'x' 
      }));
    })
}


ikarasz
  • 253
  • 2
  • 10
0

Try this:

{
    this.props.tasks.map(i=>{
        return (
            data.push({
                name: i.name,
                [`${parseInt(i.start, 10)}`]: 'x',
                [`${parseInt(i.end, 10)}`]: 'x'
            })
        );
    })
}

Bracket notation uses a string but you can produce the string using any legal javascript code. You may specify the string as literal or use a variable or calculate in some way.

Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17