将两个数组合并为多个对象

问题描述

我已经有一个对象女巫有两个数组:

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'
        },]

请注意,我需要有 iconname 键。

这在 js 中是否可行?

解决方法

这应该有效

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);

确保两个数组的长度相同并且都是有序的

,

使用 index 的简单 forEach 循环就可以了

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)

,

const services={iconAndLink:["Icon1",name:["Name1","Name3"]};
    
const res = services.name.map((e,i) => ({
  icon: e,name: services.iconAndLink[i]
}))

console.log(res)

,

假设数组大小相同,您可以:

const services = { iconAndLink: [ 'Icon1',name: [ 'Name1',};
const newArr = [];

for (let i = 0; i < services.iconAndLink.length; i++) {
    newArr.push({icon: services.iconAndLink[i],name: services.name[i]})
}

console.log(newArr)