1

Should be a simple answer, could be that my syntax is not correct since I am new to ReactJS. I would like to assign a unique id as the key.

This throws an error:

rows:{
  uniqueId() : { name:"Kitchen Remodel", value:20100 },
  uniqueId() : { name:"Basement Remodel", value:8300 }
}

This does not? Please explain...

rows:{
  143434 : { name:"Kitchen Remodel", value:20100 },
  984578 : { name:"Basement Remodel", value:8300 }
}

Thanks!

Umang Gupta
  • 15,022
  • 6
  • 48
  • 66
Paul
  • 1,527
  • 2
  • 16
  • 24
  • 1
    _the array of objects in an object_? You can make your example work in new and modern JS by using `[uniqueId()]` so that the name of the key is evaluated, but I don't really understand what your goal is. – Tom Fenech Mar 16 '17 at 16:02
  • This question doesn't seem to be anything specific to ReactJS, and it seems to already have some answers here: http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal – Candy Gumdrop Mar 16 '17 at 16:02
  • Candy thanks, that question seems to be on point. – Paul Mar 16 '17 at 16:10

2 Answers2

2

In ES6, you can use a function call or variable for the property name like so:

rows:{
  [uniqueId()] : { name:"Kitchen Remodel", value:20100 },
  [uniqueId()] : { name:"Basement Remodel", value:8300 }
}
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

Left hand side cannot be evaluated, when you are declaring an object like this.

You might want to do declare/assign like below

var row = {}; 
row[unique_id()] = { name:"Kitchen Remodel", value:20100 };
row[unique_id()] = { name:"Basement Remodel", value:8300 };
Umang Gupta
  • 15,022
  • 6
  • 48
  • 66
  • I see. I did not know it could not be something evaluated, that makes perfect sense. Thanks for the explanation. – Paul Mar 16 '17 at 15:59
  • This is more a JS (language) phenomenon than React (library). You might want to edit/update your question. – Umang Gupta Mar 16 '17 at 16:00
  • I was not sure if it was an issue with the uniqueId() function. – Paul Mar 16 '17 at 16:04