Paul
Paul

Reputation: 1545

Javascript setting uniqueId() as array keys

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!

Upvotes: 1

Views: 32

Answers (2)

MrCode
MrCode

Reputation: 64526

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 }
}

Upvotes: 2

Umang Gupta
Umang Gupta

Reputation: 16450

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 };

Upvotes: 0

Related Questions