In your reply to my question "Is it important that you discover the names of the properties in this.state.inputs dynamically, or is it okay to list them literally?", you've said:
it's ok to list them literally. I know I can do it with a loop. I just want to know if there's any possibility.
Absolutely, no need for a loop at all, direct assignment is the simple, direct approach:
user.employee_count_range = this.state.inputs.employee_count_range.value;
user.phone = this.state.inputs.phone.value;
user.city = this.state.inputs.city.value;
Live example (using state rather than this.state):
const state = {
inputs: {
employee_count_range: {
value: 42
},
phone: {
value: "123 456 7890"
},
city: {
value: "London"
}
}
};
const user = {};
user.employee_count_range = state.inputs.employee_count_range.value;
user.phone = state.inputs.phone.value;
user.city = state.inputs.city.value;
console.log(user);
You can also use destructuring assignment to do it, but it doesn't buy you much of anything and it can be tricky to read:
({
employee_count_range: {value: user.employee_count_range},
phone: {value: user.phone},
city: {value: user.city}
} = this.state.inputs);
Live example (using state rather than this.state):
const state = {
inputs: {
employee_count_range: {
value: 42
},
phone: {
value: "123 456 7890"
},
city: {
value: "London"
}
}
};
const user = {};
({
employee_count_range: {value: user.employee_count_range},
phone: {value: user.phone},
city: {value: user.city}
} = state.inputs);
console.log(user);
All of the below assumes you want to find the property names dynamically, which it now turns out isn't the case.
If you mean you want to replicate this:
Object.keys(this.state.inputs)
.map(field => user[field] = this.state.inputs[field].value);
...without any form of looping construct at all, then no, there's no way to do that. You'll need some kind of loop.
map isn't the right choice, though, because you're not using its return value. forEach or a for-of loop would be more appropriate choices:
Object.keys(this.state.inputs)
.forEach(field => user[field] = this.state.inputs[field].value);
or
for (const field of Object.keys(this.state.inputs)) {
user[field] = this.state.inputs[field].value;
}
You can avoid the second lookup (this.state.iputs[field].value) using Object.entries instead of Object.keys (but it involves a bunch of temporary arrays, so...tradeoffs):
for (const [field, value] of Object.entries(this.state.inputs)) {
user[field] = value;
}
or with forEach:
Object.entries(this.state.inputs).forEach(([field, value]) => {
user[field] = value;
});
stateobject inner values touserobject.