如何合并与其他数组中的属性匹配的对象数组

时间:2018-05-23 11:57:31

标签: arrays ecmascript-6

我想合并2个数组来创建new,它们具有基于key但无法实现的更新值。我正在寻找一种更简单的解决方案,采用es6 / es7方法。

 let selectedID = [
    {
        "id": 7,
        "selected": true
    },
    {
        "id": 1,        
        "selected": true
    }
];

let baseID = [
    {
        "id": 7,
        "selected": false
    },
    {
        "id": 12,
        "selected": false
    },
    {
        "id": 13,
        "selected": false
    },
    {
        "id": 1,
        "selected": false
    },
    {
        "id": 9,
        "selected": false
    },
    {
        "id": 10,
        "selected": false
    }
];


const op = baseID.map( b => {
    return selectedID.map( f => {
     if(f.id === s.id) {
         return f;
     } else {
      return b;
     }
   });
});

console.log(op);

但它返回一个项目数组,每个项目都是2个对象的数组。

[[ 
{id: 7, selected: true}
{id: 7, selected: false}
,[],...]

预期产出:

[{
            "id": 7,
            "selected": true
        },
        {
            "id": 12,
            "selected": false
        },
        {
            "id": 13,
            "selected": false
        },
        {
            "id": 1,
            "selected": true
        },
        {
            "id": 9,
            "selected": false
        },
        {
            "id": 10,
            "selected": false
        }
    ]

1 个答案:

答案 0 :(得分:1)

您可以find使用map来查找selectedID数组:



let selectedID = [
  {
    id: 7,
    selected: true
  },
  {
    id: 1,
    selected: true
  }
];

let baseID = [
  {
    id: 7,
    selected: false
  },
  {
    id: 12,
    selected: false
  },
  {
    id: 13,
    selected: false
  },
  {
    id: 1,
    selected: false
  },
  {
    id: 9,
    selected: false
  },
  {
    id: 10,
    selected: false
  }
];

const op = baseID.map(
  item => selectedID.find(selectedItem => item.id === selectedItem.id) || item
);

console.log(op);