简体   繁体   English

动态合并数组对象

[英]Dynamically merge array objects

I want to combine two arrays (ranking and matches) that has common properties:我想结合两个具有共同属性的 arrays (排名和匹配):

var ranking = [{
    def: "0.58",
    league: "Scottish Premiership",
    name: "Celtic",
    off: "3.33",
    grank: "3",
    tform: "96.33",
},
{
    def: "2.52",
    league: "Scottish Premiership",
    name: "Dundee",
    off: "1.28",
    grank: "302",
    tform: "27.51",
}]

var matches = [{
date: "2010-04-22",
league: "Scottish Premiership",
home: "0.0676",
away: "0.8",
draw: "0.1324",
goals1: "3",
goals2: "1",
tform1: "96.33",
tform2: "27.51",
team1: "Celtic",
team2: "Dundee",}]

Expected output looks like this:预期的 output 如下所示:

[{
date: "2010-04-22",
league: "Scottish Premiership",
home: "0.0676",
away: "0.8",
draw: "0.1324",
goals1: "3",
goals2: "1",
tform1: "96.33",
tform2: "27.51",
def1: "0.58",
def2: "2.52",
off1: "3.33",
off2: "1.28",
grank1: "3",
grank2: "302",
team1: "Celtic",
team2: "Dundee",}]

To merge the arrays, I used Lodash _.merge function为了合并 arrays,我使用了 Lodash _.merge function

var result = _.merge(ranking, matches);

The output it returned did merge some objects and omitted homogeneous objects.它返回的 output 确实合并了一些对象并省略了同类对象。

Please I need some help and insight in achieving this task.请我需要一些帮助和洞察力来完成这项任务。 I wouldn't mind any javascript (client-side) solution.我不介意任何 javascript(客户端)解决方案。

You need to merge by the given data and add the information of the two teams.您需要根据给定的数据进行合并,并添加两个团队的信息。

 const keys = ['def', 'off', 'grank'], getRanking = (team, suffix) => Object.fromEntries(keys.map(k => [k + suffix, team[k]])), ranking = [{ def: "0.58", league: "Scottish Premiership", name: "Celtic", off: "3.33", grank: "3", tform: "96.33" }, { def: "2.52", league: "Scottish Premiership", name: "Dundee", off: "1.28", grank: "302", tform: "27.51" }], matches = [{ date: "2010-04-22", league: "Scottish Premiership", home: "0.0676", away: "0.8", draw: "0.1324", goals1: "3", goals2: "1", tform1: "96.33", tform2: "27.51", team1: "Celtic", team2: "Dundee" }], teams = Object.fromEntries(ranking.map(o => [o.name, o])), result = matches.map(o => ({...o, ...getRanking(teams[o.team1], 1), ...getRanking(teams[o.team2], 2) })); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM