过滤Javascript数组并仅返回具有填充键的对象

时间:2019-03-04 01:26:11

标签: javascript arrays

我已经在这里搜索了几个小时,到目前为止仍找不到正确的答案。我很抱歉,如果答案已经在那里。

我试图过滤一个数组,只返回具有某个键且具有任何值的对象。只要该键不为空或null,值就没有关系。

数组示例:

[
  {
    "title": "Song 1",
    "author": "Joe",
    "Album1": 2,
    "Album2": null,
    "Album3": 5
  },
  {
    "title": "Song 2",
    "author": "Jane",
    "Album1": null,
    "Album2": null,
    "Album3": 8
  },
  {
    "title": "Song 3",
    "author": "Steve",
    "Album1": 10,
    "Album2": 1,
    "Album3": null
  }
]

我只想返回在Album1中具有值的对象(该值将是轨道号)。我不在乎值是多少,只要有值即可。因此,在此示例中,仅将以下内容返回到新数组:

[
  {
    "title": "Song 1",
    "author": "Joe",
    "Album1": 2,
    "Album2": null,
    "Album3": 5
  },
  {
    "title": "Song 3",
    "author": "Steve",
    "Album1": 10,
    "Album2": null,
    "Album3": null
  }
]

我尝试了几种不同的方法,每种方法均失败。这是一个看起来应该可以工作的东西,但是不起作用:

getFilteredSongs (array, album) {
  return songs
    .filter(function (obj) {
      return Object.keys(album).every(function (a) {
        return obj[a] === true
      })
    })
  }

getFilteredSongs(songsList, Album1)

我非常感谢您的协助以及对我的绿色技巧的耐心和无法找到应该解决的问题。

3 个答案:

答案 0 :(得分:2)

您需要做的就是返回Album1属性-如果null,结果数组将不包含在结果中:

const songs = [
  {
    "title": "Song 1",
    "author": "Joe",
    "Album1": 2,
    "Album2": null,
    "Album3": 5
  },
  {
    "title": "Song 2",
    "author": "Jane",
    "Album1": null,
    "Album2": null,
    "Album3": 8
  },
  {
    "title": "Song 3",
    "author": "Steve",
    "Album1": 10,
    "Album2": 1,
    "Album3": null
  }
];

const filtered = songs.filter(({ Album1 }) => Album1);
console.log(filtered);

或者,如果您不希望破坏,也可以:

const filtered = songs.filter(song => song.Album1);

或者,如果您使用getFilteredSongs string 键调用Album1

const songs = [
  {
    "title": "Song 1",
    "author": "Joe",
    "Album1": 2,
    "Album2": null,
    "Album3": 5
  },
  {
    "title": "Song 2",
    "author": "Jane",
    "Album1": null,
    "Album2": null,
    "Album3": 8
  },
  {
    "title": "Song 3",
    "author": "Steve",
    "Album1": 10,
    "Album2": 1,
    "Album3": null
  }
];
const getFilteredSongs = (songs, album) => songs.filter(song => song[album]);
console.log(getFilteredSongs(songs, 'Album1'));

答案 1 :(得分:0)

以下内容将删除所有具有null的相册。

filteredSongs = songs.filter((cur) => cur.Album1 !== null);

答案 2 :(得分:0)

如果Album1可能是undefined / null以外的虚假值(例如0),则您只能排查{{1 }} / undefined如下:

null