通过匹配值搜索辅助数组并合并到主数组中

时间:2017-09-15 11:46:04

标签: javascript arrays underscore.js

我有2个数组,我试图在第二个数组中找到与第一个数组中的对象匹配Id的数组对象。从那里我需要将匹配的对象附加到主对象。我还需要通过键值来获取前3个匹配对象。我一直在尝试使用Underscore,但这只会将匹配的数组合并在一起。 Heres是我需要实现的,任何帮助都会很棒。

var primaryArray = [
  {
    "Name": "Main 1",
    "Id": "1"
  },
  {
    "Name": "Main 2",
    "Id": "2"
  }
]


var secondaryArray = [
  {
    "name": "Person 1",
    "mainitemId": "1",
    "count": 120
  },
  {
    "name": "Person 2",
    "mainitemId": "1",
    "count": 80
  },
  {
    "name": "Person 3",
    "mainitemId": "1",
    "count": 125
  },
  {
    "name": "Person 4",
    "mainitemId": "1",
    "count": 130
  },
  {
    "name": "Person 5",
    "mainitemId": "2",
    "count": 90
  },
  {
    "name": "Person 6",
    "mainitemId": "2",
    "count": 85
  },
  {
    "name": "Person 7",
    "mainitemId": "2",
    "count": 105
  },
  {
    "name": "Person 8",
    "mainitemId": "2",
    "count": 110
  }
]


var resultArray = [
  {
    "Name": "Main 1",
    "Id": 1,
    "people": [
      {
        "name": "Person 4",
        "mainitemId": "1",
        "count": 130
      },
      {
        "name": "Person 3",
        "mainitemId": "1",
        "count": 125
      },
      {
        "name": "Person 1",
        "mainitemId": "1",
        "count": 120
      }
    ]
  },
  {
    "Name": "Main 2",
    "Id": 2,
    "people": [
      {
        "name": "Person 8",
        "mainitemId": "2",
        "count": 110
      },
      {
        "name": "Person 7",
        "mainitemId": "2",
        "count": 105
      },
      {
        "name": "Person 5",
        "mainitemId": "2",
        "count": 90
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:0)

如果你想根据 count 值得到前3名,那应该是......

var result = primaryArray.map(item => {
    item.people = secondaryArray.filter(peop => peop.mainitemId === item.Id)
                                .sort((a, b) => b.count - a.count)
                                .slice(0, 3);
    return item;        
})

最终结果:

enter image description here