javascript - 将两个数组元素合并为一个元素
问题描述
我正在尝试以下列方式组合两个数组。
var x = [{'d1':'3'}, {{'d2':'4'}}, {{'d3':'5'}}]
var y = [{'c1':'3'}, {{'c2':'4'}}, {{'c3':'5'}}]
我的结果应该是这样的
z = [
{'d1':'3', 'c1':'3' },
{'d1':'4', 'c1':'4' },
{'d1':'5', 'c1':'5' },
]
解决方案
清理你的语法,这就是我最终的结果:
let x = [{d1:'3'}, {d2:'4'}, {d3:'5'}];
let y = [{c1:'3'}, {c2:'4'}, {c3:'5'}];
// create a new list to store the objects we'll create
let z = [];
[x, y].forEach(array => {
// loop through the values for this line
for (i=0; i < array.length; i++) {
// handle case where we need to add more objects to our list
if (z.length <= i) z.push({});
// add new kay and value
z[i][Object.keys(array[i])[0]] = array[i][Object.keys(array[i])[0]];
}
});
console.log(z)
请注意,通过更改[x,y]
为更多列表(例如[x,y,z,w]
此代码),假设它们的大小都相同,它们仍然可以工作:)
在此处查看实时示例。
推荐阅读
- css - 使用具体化 css 在工具提示中显示图像
- jquery - 提交 JQuery 表单发布请求时页面不工作
- sql - psql 中输入的 SQL 命令是属于 SQL(Postgresql 的 SQL 方言)还是 PL/PgSQL?
- launch - 如何在右舷层更改 Cobalt 启动 URL 和参数?
- wpf - DataGrid Foucs 中的可编辑组合框不起作用
- angular - Angular 服务:单例、非单例、延迟加载和 ngrx。如何提供它们?
- f# - 将数据集随机拆分为较小的集合 f#
- macos - 如何将 iTerm 带到屏幕前面或后面的快捷方式
- iterm2 - 如何使用 exit 命令关闭 iterm2 选项卡?
- android - 为什么我不能在 Fragment 中使用 Listview