The array object is filtered according to a certain attribute value. If the attribute value is the same, other attributes in the object are combined into an array

The array object is filtered according to a certain attribute value. If the attribute value is the same, other attributes in the object are combined into an array

Only two methods are listed here, of course there are more methods

<script>
export default {
    
    
  data () {
    
    
    return {
    
    
      array: [
        {
    
    
          name: '土豆',
          val: '2'
        },
        {
    
    
          name: '土豆',
          val: '3'
        },
        {
    
    
          name: '马铃薯',
          val: '1'
        },
        {
    
    
          name: '西瓜',
          val: '6'
        },
        {
    
    
          name: '西瓜',
          val: '4'
        },
        {
    
    
          name: '马铃薯',
          val: '5'
        }
      ]
    }
  },
  mounted () {
    
    
  //方法一
    const temArr = []
    // name不重复的数组
    const newArr = []
    for (let i = 0; i < this.array.length; i++) {
    
    
      // 判断temArr是否存在与array数组中name相同的值,有则跳过,无则插入
      if (temArr.indexOf(this.array[i].name) === -1) {
    
    
        newArr.push({
    
    
          name: this.array[i].name,
          // 这里要写成数组的形式,后面需要将name相同的val值合并成一个数组
          valList: [this.array[i].val]
        })
        // 插入名字,防止出现相同名字的数据
        temArr.push(this.array[i].name)
      } else {
    
    
        // 循环name不重复的数组
        for (let j = 0; j < newArr.length; j++) {
    
    
          // 跟原数组进行name的比对
          if (newArr[j].name === this.array[i].name) {
    
    
          // 相同,将val值插入valList数组
            newArr[j].valList.push(this.array[i].val)
          }
        }
      }
    }
    console.log(newArr)
// 方法二
    const newArr = {
    
    }
    this.array.forEach((item) => {
    
    
      if (!newArr[item.name]) {
    
    
        newArr[item.name] = {
    
    
          name: item.name,
          valList: []
        }
      }
      newArr[item.name].valList.push(item.val ? item.val : '')
    })
// 方法n...
  }
}
</script>

insert image description here

Guess you like

Origin blog.csdn.net/JunVei/article/details/126743491