我有一个具有参与者和partnersIdentities数组属性的对象。这两个属性都有参与者ID属性。如何链接它们?

时间:2019-07-08 19:17:48

标签: javascript vue.js vuejs2

我目前正在遍历一些参与者,并使用Vue.js v-for显示每个参与者的统计信息,但是,我还想显示该参与者的summonerName及其统计信息。问题在于有关用户的信息包含在partnerIdentities中,但是他的统计信息包含在参与者中。我假设我可以使用两种情况下都存在的participantId属性来链接两个属性,但是,我不确定该怎么做。任何提示和指示,将不胜感激。

<div class='participant' v-for='participant in match.details.participants'>
    <p>{{ participant.stats.kills }}/</p>
    <p>{{ participant.stats.deaths }}/</p>
    <p>{{ participant.stats.assists }}</p>
</div>

对象的相关属性如何显示:

details: Object
    participantIdentities: Array(10)
        0:
            participantId: 1
            player: Object
                summonerName: "Test"
                summonerIcon: 1337
    participants: Array(10)
        0:
            participantId: 1
            stats: Object

2 个答案:

答案 0 :(得分:0)

您基本上希望基于属性对两个对象数组执行联接。我喜欢从数组创建Map,然后使用object spread syntax将它们连接在一起。这样完成:

var a = [{id: 1, name: 'johnny'}, {id: 2, name: 'joey'}];
var b = [{id: 1, type: 24152}, {id: 2, type: 325723}];

// convert the arrays to key/value pair where the key is the id and the value is the object itself 
var mapA = new Map(a.map(x => [x.id, x]));
var mapB = new Map(b.map(x => [x.id, x]));

const merged = [];
for (var [key, val] of mapA) { // iterate through the values of mapA
	merged.push({...val, ...mapB.get(key)}); // Join the object from mapA with the object from mapB using the spread operator 
}

console.log(merged)

答案 1 :(得分:0)

您可以按ID对数组进行排序

participants.sort(function(a, b){return a.id - b.id});
participantIdentities.sort(function(a, b){return a.id - b.id});

然后,您可以将索引添加到v-for中并获取数组元素

<div class='participant' v-for='(participant, index) in 
match.details.participants'>
    <p>{{ participant.stats.kills }}/</p>
    <p>{{ participant.stats.deaths }}/</p>
    <p>{{ participantIdentities[index].player.summonerName }}</p>
</div>