如果我的state
对象是这样的,
this.state={
input:{
employee_count_range: {
value: props.employee_count_range || '',
errMsg: null
},
phone: {
value: '',
errMsg: null
},
city: {
value: '',
errMsg: null
}
}
}
和user
对象是这样的,
let user = {
employee_count_range: '',
phone: '',
city: ''
}
有没有办法不用循环就可以用 ES6 做到这一点?
Object.keys(this.state.inputs)
.map(field => user[field] = this.state.input[field].value);
我想将 state
对象分配给 value
中的每个 user
对象值
最佳答案
在你对我的问题的回复中“动态地发现 this.state.inputs 中的属性名称重要吗,或者可以按字面列出它们吗?”,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.
当然,根本不需要循环,直接赋值是最简单、直接的方法:
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;
实例(使用 state
而不是 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);
您也可以使用解构赋值来做到这一点,但它不会给您带来太多好处,而且阅读起来可能很棘手:
({
employee_count_range: {value: user.employee_count_range},
phone: {value: user.phone},
city: {value: user.city}
} = this.state.inputs);
实例(使用 state
而不是 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);
以下所有内容均假定您希望动态查找属性名称,但事实并非如此。
如果你的意思是你想复制这个:
Object.keys(this.state.inputs)
.map(field => user[field] = this.state.inputs[field].value);
...根本没有任何形式的循环结构,那么不,没有办法做到这一点。您将需要某种循环。
但是,
map
不是正确的选择,因为您没有使用它的返回值。 forEach
或 for-of
循环将是更合适的选择:
Object.keys(this.state.inputs)
.forEach(field => user[field] = this.state.inputs[field].value);
或
for (const field of Object.keys(this.state.inputs)) {
user[field] = this.state.inputs[field].value;
}
您可以使用 Object.entries
而不是 Object.keys
来避免第二次查找 (this.state.iputs[field].value
) >(但它涉及一堆临时数组,所以......权衡):
for (const [field, value] of Object.entries(this.state.inputs)) {
user[field] = value;
}
或使用forEach
:
Object.entries(this.state.inputs).forEach(([field, value]) => {
user[field] = value;
});
关于javascript - 如何在不通过循环的情况下将对象与 JavaScript 中的其他对象内部值合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51515885/