javascript - 如何在不通过循环的情况下将一个对象与 JavaScript 中的其他对象内部值合并?
问题描述
如果我的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 中的属性名称是否重要,或者按字面意思列出它们是否可以?”的回答中 ,你说过:
可以按字面意思列出它们。我知道我可以用循环来做到这一点。我只想知道有没有可能。
当然,根本不需要循环,直接赋值是简单直接的方法:
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;
}
this.state.iputs[field].value
您可以使用Object.entries
而不是避免第二次查找( ) Object.keys
(但它涉及一堆临时数组,所以...权衡):
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;
});
推荐阅读
- angular - 使用 ngx-bootstrap 将任何组件传递给我的模态
- python - 标记数组中的唯一行
- sql - 当值不是 1 时,MariaDB 阻止删除
- python - 获取所有模型文件的最佳方法
- wso2-am - 动态端点的故障转移 url 配置
- regex - Spring RequestMapping 正则表达式:将所有不带点 [.] 的 url 转发到 index.html
- flutter - 我正在尝试计算物品清单的总价
- python - 向月份和日期列添加零时出错
- android - flutter<->android 通信开销
- collections - 更新pymongo中集合列表项中的值