发布于 5年前

JavaScript 对象数组,如何筛选出有相同key的对象

问题描述

我有下面这样一个数组, 数组里面每个对象有三个相同的 key :name、age、hair。

let namelist = [{
  name: 'mark',
  age: 15,
  hair: 'long'
}, {
  name: 'tuwen',
  age: 16,
  hair: 'short'
}, {
  name: 'xiaoming',
  age: 16,
  hair: 'short'
}, {
  name: 'lilei',
  age: 15,
  hair: 'short'
}, {
  name: 'hanmei',
  age: 17,
  hair: 'long'
}]

筛选条件:数组中age相同的对象分到一个数组里。

期望结果

arr_1 = [{
  name: 'mark',
  age: 15,
  hair: 'long'
}, {
  name: 'lilei',
  age: 15,
  hair: 'short'
}]

arr_2 = [{
  name: 'tuwen',
  age: 16,
  hair: 'short'
}, {
  name: 'xiaoming',
  age: 16,
  hair: 'short'
}]

arr_3 = [{
  name: 'hanmei',
  age: 17,
  hair: 'long'
}]

最佳答案

let res = []
while(nameList.length!==0){
  let list = nameList.shift()
  let arr = [list]
  for (let i = 0; i < nameList.length; i++) {
    if (nameList[i].age === list.age) {
      arr = arr.concat(nameList.splice(i, 1))
      i--
    }
  }
  res.push(arr)
}
©2020 edoou.com   京ICP备16001874号-3