1

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';
};
5
  • 2
    state.state1 = state.state2 = state.state3 = 'same-value'; this is the only way that comes to my mind. Commented Jan 14, 2020 at 13:15
  • 1
    What is the use-case you're after? Commented Jan 14, 2020 at 13:23
  • JSON.parse('{' + '"state,'.repeat(30).split(',').map(function(v, i, a){return v ? v + ++i : null}).join('":"same-value",').slice(0, -1) + '}') :-D Commented Jan 14, 2020 at 13:44
  • @Lain get with the times Commented Jan 14, 2020 at 13:58
  • @VLAZ: Going with time makes me feel old :-( Commented Jan 14, 2020 at 14:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.