关于数组的小问题

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 相等的项

阅读 1.7k
3 个回答
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"}
// ================

你要实现啥效果?循环遍历一下?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题