H5W3
当前位置:H5W3 > 其他技术问题 > 正文

【Web前端问题】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)
}

回答:

我的思路是先使用map得到所有的age

let one = namelist.map(function(e){
    return e.age
})

然后去重

    new Set(one)

然后用filter方法,得到你想要的各个数组集合

回答:

const mapChatList = (a) => {
  let result = Object.values(a.reduce((m, n) => {
    if (!m[n.age]) {
      m[n.age] = {age: n.age, list: []}
    }
    m[n.age].list.push(n)
    return m
  }, {}))

  return result.map(item=>item.list)

}

mapChatList(namelist)

回答:

let dic = {};
let {arr1, arr2, arr3} =  namelist.reduce((target, item)=>{
        if(!dic[item["age"]]){
            dic[item["age"]] = Object.keys(target).length + 1;
            target['arr'+dic[item["age"]]] = [];
        }
        target['arr'+dic[item["age"]]].push(item);
        return target;
    }, {});

回答:

const 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'
}]

const key = 'age'
const keys = getSameValKey(namelist, key)
const result = sortData(namelist, keys, key)
console.log(JSON.stringify(result))
/*
{
  "15":[{"name":"mark","age":15,"hair":"long"},{"name":"lilei","age":15,"hair":"short"}],
  "16":[{"name":"tuwen","age":16,"hair":"short"},{"name":"xiaoming","age":16,"hair":"short"}],
  "17":[{"name":"hanmei","age":17,"hair":"long"}]
}
*/

function getSameValKey(arry, key) {
    const set = new Set()
    arry.forEach(item => {
        set.add(item[key])
    })

    return [...set]
}

function sortData(arry, keys, key) {
    const map = {}
    keys.forEach(key => {
        map[key] = []
    })

    arry.forEach(item => {
        map[item[key]].push(item)
    })

    return map
}

回答:

声明obj保存对象,遍历,如果已经存在以age为key的项,直接push到数组里,没有则创建数组,再push。
最后的obj是这种形式。调用的话,由于key是number,可以用obj[15]调用。
clipboard.png

let obj = {};
namelist.forEach(function(item){
    if(obj[item.age]){
        obj[item.age].push(item);
    }else{
        obj[item.age] = [];
        obj[item.age].push(item);
    }
})
console.log(obj);

回答:

// 我们输出一个以 `age_${namelist.age}` 作为 key 值的对象集合
const classify = list => list.reduce((result, currentItem) => {
    (result[`age_${currentItem.age}`] || (result[`age_${currentItem.age}`] = [])).push(currentItem)
    return result
}, {})

classify(namelist)

回答:

不好意思,我来晚了,不过我还是提供一种 es6的方式吧,仅供参考

let map = new Map()

namelist.forEach(item => {
    if (map.has(item.age)) {
        map.set(item.age, map.get(item.age).concat(item))
    } else {
        map.set(item.age, [item]) 
    }
})

console.log(map)

const [arr1, arr2, arr3] = [...map]

本文地址:H5W3 » 【Web前端问题】JavaScript 对象数组,如何筛选出有相同key的对象

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址