微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将两个数组合并为多个对象

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

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。