在JavaScript中,如何在不经过循环的情况下将对象与其他对象内部值合并?
如果我的在JavaScript中,如何在不经过循环的情况下将对象与其他对象内部值合并?,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,如果我的状态对象是这样的 this.state={ input:{ employee_count_range: { value: props.employee_count_range || '', errMsg: null }, phone: { value: '', errMsg: null }, city: { value: '', errMsg: nu
状态
对象是这样的
this.state={
input:{
employee_count_range: {
value: props.employee_count_range || '',
errMsg: null
},
phone: {
value: '',
errMsg: null
},
city: {
value: '',
errMsg: null
}
}
}
let user = {
employee_count_range: '',
phone: '',
city: ''
}
而user
对象是这样的
this.state={
input:{
employee_count_range: {
value: props.employee_count_range || '',
errMsg: null
},
phone: {
value: '',
errMsg: null
},
city: {
value: '',
errMsg: null
}
}
}
let user = {
employee_count_range: '',
phone: '',
city: ''
}
有没有任何方法可以在不经过循环的情况下使用ES6实现这一点
Object.keys(this.state.inputs)
.map(field => user[field] = this.state.input[field].value);
我想在您回答我的问题“动态发现this.state.inputs中的属性名称是否重要,或者可以逐字列出它们?”时,将
state
值中的每个对象分配给用户对象值:
可以逐字列出它们。我知道我可以做一个循环。我只是想知道有没有可能
绝对不需要循环,直接赋值是一种简单、直接的方法:
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={
投入:{
员工人数范围:{
价值:42
},
电话:{
值:“123 456 7890”
},
城市:{
价值:“伦敦”
}
}
};
const user={};
user.employee\u count\u range=state.inputs.employee\u count\u range.value;
user.phone=state.inputs.phone.value;
user.city=state.inputs.city.value;
console.log(用户)代码>你想要的输出是什么?不进入循环意味着-根本没有循环(没有映射forEach等)或没有for/while循环?@narendrajadv我想将状态对象内部值分配给用户对象。@Lasitha-我的问题包含两个选项。他们哪一个是对的?@OriDrori没有地图,foreach,for/while loop我感谢你在这个问题上花费的时间和精力。@Lasitha-不用担心。根据您对我对该问题的评论的回复,我刚刚更新了答案。:-)