javascript - 如何将字符串数组复制到对象中
问题描述
我有一个字符串数组和一个对象:
const arr = ['abc', 'def'];
const obj = {
foo: true,
bar: 42,
};
我需要将值添加为 中arr
的键obj
,以便生成的对象如下所示:
const result = {
foo: true,
bar: 42,
abc: true,
def: true,
};
这是我尝试过的:
{ ...obj, ...arr.map(x => ({[x]: true })) }
解决方案
你可以简单地使用Object.assign()
:
下面给出的示例将改变原始对象:
let arr = ['abc', 'def'];
let obj = {
foo: true,
bar: 42,
};
// Note it will mutate the original object
arr.forEach((e)=> Object.assign(obj, {[e] :true }));
console.log(obj);
如果您不想改变原始对象,请尝试以下操作:
let arr = ['abc', 'def'];
let obj = {
foo: true,
bar: 42,
};
let result = Object.assign({}, obj);
arr.forEach((e)=> Object.assign(result, {[e] :true }));
console.log(result);
推荐阅读
- exception - 我在 Ada 中遇到了 TASKING_ERROR
- leaflet - 如何在标记定义中使用传单图标定义?
- cube.js - 无法使用 cube.js 连接到 mongodb attlas
- wildfly - 使用 add-user.bat/add-user.sh 在 wildfly 中添加用户不会写入 mgmt-users.properties
- c++ - 有没有一种理想的方式来避免这种裸新的使用?
- mysql - 通过 React 和 Node.js 将未定义的值传递给 MySQL 数据库
- reactjs - React & Searchkit 显示更多按钮而不是默认分页
- c - connect() 在使用 IPv4 协议的套接字编程中失败
- html - 使用 display flex 在左侧放置一个 div,在右侧放置两个 div
- python - NoReverseMatch at / Reverse for 'article' with arguments '('',)' 未找到。尝试了 1 种模式:['blog/(?P
[0-9]+)$']