过滤一个对象数组返回空数组

时间:2018-05-10 23:40:39

标签: javascript arrays object filter

我有以下对象数组:

arr = [
    {
        name: "john",
        age: 24,
        gender: "male"
    },
    {
        name: "jane",
        age: 27,
        gender: "female"
    },
    {
        name: "joe",
        age: 29,
        gender: "male"
    }
]

我正在尝试将nameage属性过滤为新数组。我试过这个:

const newFields = arr.filter((item) => {
    return (
        item.name && item.age
    );
});

但由于某种原因newFields返回一个空数组。

1 个答案:

答案 0 :(得分:2)

而不是.filter()使用.map()



const arr = [
  {
    name: "john",
    age: 24,
    gender: "male"
  },
  {
    name: "jane",
    age: 27,
    gender: "female"
  },
  {
    name: "joe",
    age: 29,
    gender: "male"
  }
];

const newFields = arr.map(item => {
  return {
      name: item.name,
      age: item.age
    }
});
console.log(newFields)