javascript - 通过键合并对象并创建新的键名
问题描述
我有 2 个对象数据。
let continent = {
"BD": "AS",
"BE": "EU",
"BF": "AF",
"BG": "EU"
}
let capital = {
"BD": "Dhaka",
"BE": "Brussels",
"BF": "Ouagadougou",
"BG": "Sofia"
}
我想像这样合并它
{
"BD": {
"continent": "AS",
"capital": "Dhaka",
},
"BE": {
"continent": "EU",
"capital": "Brussels",
},
"BF": {
"continent": "AF",
"capital": "Ouagadougou",
},
"BG": {
"continent": "EU",
"capital": "Sofia",
}
}
我不知道如何实现它。
先感谢您。
解决方案
您可以与以下函数合并,只需确保以与对象相同的顺序传递键名。您可以使用以下方法合并任意数量的对象。
let continent = {
"BD": "AS",
"BE": "EU",
"BF": "AF",
"BG": "EU"
};
let capital = {
"BD": "Dhaka",
"BE": "Brussels",
"BF": "Ouagadougou",
"BG": "Sofia"
};
function merge() {
const args = Array.from(arguments);
const keys = args.filter(e => 'string' === typeof e);
const objs = args.filter(e => 'object' === typeof e);
return objs.reduce((a, b, i) => {
Object.entries(b).forEach(([key, value]) => {
if (! a[key]) {
a[key] = {[keys[i]]: value}
} else {
a[key][keys[i]] = value;
}
});
return a;
}, {})
}
console.log(merge('continent', 'capital', continent, capital));
不用过滤可能更容易使用arguments
function merge(keys, objects) {
return objects.reduce((a, b, i) => {
Object.entries(b).forEach(([key, value]) => {
if (! a[key]) {
a[key] = {[keys[i]]: value}
} else {
a[key][keys[i]] = value;
}
});
return a;
}, {})
}
console.log(merge(['continent', 'capital'], [continent, capital]));
要省略编写每个键,您还可以将参数作为对象数组传递,如下所示。这需要将变量命名为所需的键。
function merge(data) {
return data.reduce((a, b, i) => {
const key = Object.keys(b)[0];
Object.entries(b[key]).forEach(([k, v]) => {
if (!a[k]) {
a[k] = {[key]: v}
} else {
a[k][key] = v;
}
});
return a;
}, {})
}
console.log(merge([{continent}, {capital}]));
推荐阅读
- mysql - mysql 选择这个公式 E < X <=2E & X > 3E
- swift - 变量名与内置函数冲突
- matlab - 文件标识符可以在 Matlab fprintf 中指定一个字符串作为输出吗?
- macos - webcal:// 链接不再在 MacOS 上打开 Apple 日历
- javascript - 如何使用外部 HTML 文件制作 Web 组件?
- c++ - 如何在 c++11 中的默认移动构造函数末尾添加打印语句?
- python-3.x - 如何在 AWS Cloud9 中安装 chromedriver?
- git - 如何使用 XAMPP 在 Windows 10 上修复 git-backend-http 的重定向问题
- puppet - Puppet Enterprise 中无法识别的服务
- javascript - 无法获取 javascript 天气 api 应用程序来显示天气