javascript - 如何过滤数组并获取整个数据条目?

标签 javascript arrays

我有,

[
  {
    _id: 60673d40ba14f617081bdf4d,
    ImageName: 'Flowers',
    ImagePath: './public/assets/img/1.jpg',
    Description: 'A cool Image',
    __v: 0
  },
  {
    _id: 60673e099d76ef16a8ec4588,
    ImageName: 'Water Bubble Colors',
    ImagePath: './public/assets/img/2.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: 60673e39f10c4a12a0f4ea31,
    ImageName: 'Egg Silhouette Wallpaper',
    ImagePath: './public/assets/img/3.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: 60673e4a15d9bb18a01312df,
    ImageName: 'Pencil BW ',
    ImagePath: './public/assets/img/4.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: 60673e6c6de9bb1bf8c65d25,
    ImageName: 'Water',
    ImagePath: './public/assets/img/5.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: 60673e8a8af58b1fb8b11596,
    ImageName: 'Dining Plate',
    ImagePath: './public/assets/img/6.jpg',
    Description: 'Wallpapers',
    __v: 0
  }
]

var id = req.params.id 基本上是 60673e8a8af58b1fb8b11596。 现在如何使用我拥有的 id 变量过滤数组并获得具有 id 的整个对象?我想要带有 _id、ImageName、ImagePath、__v 和 Description 的整个对象。

我搜索了很多,找到了 array.filter 方法,但是它太复杂了,没有帮助我,我更加困惑了。

最佳答案

您可以尝试使用 Array.prototype.filter()检查 ID:

var data = [
  {
    _id: '60673d40ba14f617081bdf4d',
    ImageName: 'Flowers',
    ImagePath: './public/assets/img/1.jpg',
    Description: 'A cool Image',
    __v: 0
  },
  {
    _id: '60673e099d76ef16a8ec4588',
    ImageName: 'Water Bubble Colors',
    ImagePath: './public/assets/img/2.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: '60673e39f10c4a12a0f4ea31',
    ImageName: 'Egg Silhouette Wallpaper',
    ImagePath: './public/assets/img/3.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: '60673e4a15d9bb18a01312df',
    ImageName: 'Pencil BW ',
    ImagePath: './public/assets/img/4.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: '60673e6c6de9bb1bf8c65d25',
    ImageName: 'Water',
    ImagePath: './public/assets/img/5.jpg',
    Description: 'Wallpapers',
    __v: 0
  },
  {
    _id: '60673e8a8af58b1fb8b11596',
    ImageName: 'Dining Plate',
    ImagePath: './public/assets/img/6.jpg',
    Description: 'Wallpapers',
    __v: 0
  }
]
var id = '60673e8a8af58b1fb8b11596'; //req.params.id

var res = data.filter(d => d._id == id);
console.log(res);

关于javascript - 如何过滤数组并获取整个数据条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66929103/

相关文章:

Javascript:以前的属性未定义

javascript - 将 angularjs 应用程序嵌入另一个 angularjs 应用程序

iphone - 在 SQLite 中保存数组的最佳方法是什么?

java - 向 Java gui 添加方法

arrays - 将文件内容加载到静态字节数组中

javascript - yui 压缩器给出有效 javascript 语法的语法错误

javascript - 将链式方法附加到 JavaScript 中的元素集合

javascript - 防止键盘缩小视口(viewport)

ios - 单元格后的删除线 UITableViewCell 文本字段是 "complete"

c++ - 如何检查数组是否包含多个元素?