提问人:HenrijsS 提问时间:5/29/2021 更新时间:5/29/2021 访问量:247
将两个数组合并为多个对象
Merge two arrays to multiple objects
问:
我已经有一个对象女巫有两个数组:
const services = {
iconAndLink: [
'Icon1',
'Icon2',
'Icon3',
],
name: [
'Name1',
'Name2',
'Name3',
],
};
我研究了 Object.assign()、array.reduce()、map 等......并且似乎无法在这里找到一个像样的答案来合并这两者。
对于最终结果,我需要:
services = [
{
icon: 'Icon1',
name: 'Name1'
},
{
icon: 'Icon2',
name: 'Name2'
},
{
icon: 'Icon3',
name: 'Name3'
},
]
请注意,我需要有 和 键。icon
name
这在 js 中可能吗?
答:
1赞
Kinglish
5/29/2021
#1
一个简单的forEach循环就可以了index
const services = {
iconAndLink: [
'Icon1',
'Icon2',
'Icon3',
],
name: [
'Name1',
'Name2',
'Name3',
],
};
let newarray = [];
services.iconAndLink.forEach((el, index) => newarray.push({
icon: el,
name: services.name[index]
})
);
console.log(newarray)
4赞
Daniel Ramos
5/29/2021
#2
这应该有效
const services = {
iconAndLink: ["Icon1", "Icon2", "Icon3"],
name: ["Name1", "Name2", "Name3"],
};
let result = services.iconAndLink.map(function (icon, index) {
return { icon: services.iconAndLink[index], name: services.name[index] };
});
console.log(result);
确保两个数组的长度相同,并且都是有序的
评论
0赞
HenrijsS
5/29/2021
@Kinglish用 forEach 发布了这个。这与使用地图有什么区别?
1赞
Daniel Ramos
5/29/2021
两者都是相似的,但不同。Map 是更多的功能方式,并创建一个新的数组。forEach 允许您更改原始数组。map 函数将接收一个函数,该函数将在数组上的每个项目上运行,并使用所有创建的对象创建一个新数组。您可以在此处阅读更多内容 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/...对于性能点,地图略快(如下所示:morioh.com/p/b2d058745cb8)
1赞
ulou
5/29/2021
#3
const services={iconAndLink:["Icon1","Icon2","Icon3"],name:["Name1","Name2","Name3"]};
const res = services.name.map((e, i) => ({
icon: e,
name: services.iconAndLink[i]
}))
console.log(res)
1赞
Most Noble Rabbit
5/29/2021
#4
假设数组大小相同,您可以执行以下操作:
const services = { iconAndLink: [ 'Icon1', 'Icon2', 'Icon3', ], name: [ 'Name1', 'Name2', 'Name3', ], };
const newArr = [];
for (let i = 0; i < services.iconAndLink.length; i++) {
newArr.push({icon: services.iconAndLink[i], name: services.name[i]})
}
console.log(newArr)
评论
services
const
map()