关于数组的小问题

var arr = [
    {      type: 1,      age: 12,      name: 'xiaohua'
    },
    {      type: 1,      age: 12,      name: 'xiaoming'
    },
    {      type: 1,      age: 12,      name: 'xiaohong'
    },
    {      type: 2,      age: 14,      name: 'xiaoxiao'
    },
  ]

在一个数组内,如何判断type和age 相等的项

慕田峪4524236
浏览 93回答 2
2回答

米琪卡哇伊

let arr = [     {      type: 1,       age: 12,      name: 'xiaohua'     },     {      type: 1,       age: 12,      name: 'xiaoming'     },     {      type: 1,       age: 12,      name: 'xiaohong'     },     {      type: 2,       age: 14,      name: 'xiaoxiao'     },     {      type: 11,       age: 11,      name: 'xixi'     }, ] const res = arr.filter(ele=>ele.type===ele.age); console.log(res);这样?

繁星点点滴滴

// 生成二级映射var map = arr.reduce((p, c) => [ p[c.type] = p[c.type] || {},                                  p[c.type][c.age] = p[c.type][c.age] || [],                                  p[c.type][c.age].push(c), p][3], {})// 根据映射的节点信息获取筛选后的数组列表                                 Object.keys(map).forEach(key => {    Object.keys(map[key]).forEach(sKey =>          map[key][sKey].forEach(i => console.log(i))     )    console.log("================") })// {type: 1, age: 12, name: "xiaohua"}// {type: 1, age: 12, name: "xiaoming"}// {type: 1, age: 12, name: "xiaohong"}// ================// {type: 2, age: 14, name: "xiaoxiao"}// ================
打开App,查看更多内容
随时随地看视频慕课网APP