【问题标题】:How to not display duplicates from many objects in an Array如何不显示数组中许多对象的重复项
【发布时间】:2019-06-23 03:17:41
【问题描述】:

如何确保模板中的 vue 不显示重复项?
在我的情况下,数据是一个对象数组和键,它具有一个对象的值,其中包含多个对象。所以这将是 vue 模板语法中的嵌套 v-for。

{
    "matches": [ 
        {
            "birthday": "1/29/2019",
            "household": {
               "0": {
                    "relationship": "brother"
                 },
               "1": {
                "relationship": "brother"
                 }
            }
        }
    ]
}


我只想显示每个家庭的 1 个唯一关系。请参阅小提琴以进行进一步检查https://jsfiddle.net/sxmhv3t7/

【问题讨论】:

  • 我已经注意到有人对此表示反对。如果有更好的方法来问这个问题,请告诉我。

标签: javascript json vue.js


【解决方案1】:

您可以稍微处理一下数据,并在 matches 数组中的每个匹配项上创建一个 uniqueHouseholdMembers 数组属性,然后打印出这些值:

matches.forEach(match => {
  let houseHolds = Object.values(match.household);

  match.uniqueHouseholdMembers = houseHolds.reduce((acc, household) => {
    // check if household member has already been added to our growing list
    let isUniqueRelationship = !acc.includes(household.relationship);

    // add household member if unique
    if (isUniqueRelationship) {
      acc.push(household.relationship);
    }

    return acc;
  }, []);
});

// output using the data you provided:
// match[0].uniqueHouseholdMembers -> ['brother']
// match[1].uniqueHouseholdMembers -> ['sister']

// and if you have a 3rd match entry with more household members:
// match[2].uniqueHouseholdMembers -> ['brother', 'father', 'stranger']

【讨论】:

    【解决方案2】:

    您可以使用computed 属性使matches 数组唯一。

    例如:

      computed: {
        uniqueMatches () {
           return this.matches.map(item => {
             let households = Object.values(item.household)
             let relationships = households.map(item => item.relationship)
             const uniqueRelationships = [...new Set(relationships)]
             item.household = uniqueRelationships.reduce((acc, cur, idx) => {
                acc[idx] = {}
                acc[idx].relationship = cur
                return acc
              }, {})
              console.log(item)
             return item
           })
        }
      }
    

    然后在模板中使用uniqueMatches 而不是matches

    jsfiddle中的演示

    【讨论】:

    • 谢谢你,这正是我想要的!
    猜你喜欢
    • 2020-10-06
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多