By grecdev

2020-01-14 13:12:29 8 Comments

i want to know if i can set the same value for multiple keys in the following:

  1. React functional component state:
const [state, setState] = useState(
key1: 'same-value',
key2: 'same-value',
key3: 'same-value'
  1. React class component state:
state = {
 key1: 'same-value',
 key2: 'same-value',
 key3: 'same-value'
  1. Javascript object:
const state = {
 key1: 'same-value',
 key2: 'same-value',
 key3: 'same-value'

I want to know if something like this is possible:

const state = {
 state1, state2, state3: 'same-value';


@T.J. Crowder 2020-01-14 13:16:28

I want to know if something like this is possible

Not in an object literal, no. You can do it after creating the object:

const state = {};
state.key1 = state.key2 = state.key3 = 'same-value';

Or you could make key2 and key3 accessor properties for key1, meaning they'd track its value (change key1, and you see the change in key2 and key3), because although using them looks like a simple property access, in fact it's a function call.

const state = {
    key1: 'some-value',
    get key2() { return this.key1; },
    get key3() { return this.key1; }
console.log(state.key1); // 'some-value'
console.log(state.key2); // 'some-value'
console.log(state.key3); // 'some-value'

I'm not suggesting that, just noting it's possible.

@grecdev 2020-01-15 05:41:25

Ok thank you, another great lesson learned from stack community :)

Related Questions

Sponsored Content

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6260183 View
  • 7816 Score
  • 93 Answer
  • Tags:   javascript arrays

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

68 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

20 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

  • 2009-07-08 13:21:32
  • Adam Ernst
  • 1866170 View
  • 2818 Score
  • 20 Answer
  • Tags:   javascript object

42 Answered Questions

[SOLVED] Detecting an undefined object property

86 Answered Questions

[SOLVED] How do JavaScript closures work?

54 Answered Questions

4 Answered Questions

Sponsored Content