为了账号安全,请及时绑定邮箱和手机立即绑定

通过Javascript中的乱序ID数组过滤对象数组

通过Javascript中的乱序ID数组过滤对象数组

白衣染霜花 2021-11-12 15:35:54
这是一组书籍对象。const books=[    {      "id": 1,      "title": "NPR",      "url": "https://www.npr.org"    },    {      "id": 2,      "title": "Google Docs",      "url": "https://docs.google.com/"    },    {      "title": "Fetch API Docs",      "url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",      "id": 3    },    {      "title": "Yahoo",      "url": "http://www.yahoo.com",      "id": 4    },    {      "title": "Google",      "url": "http://www.google.com",      "id": 5    }  ]和一个单独的 ID 数组const selectedIds = [1, 5, 3]使用 javascript,如何将书籍数组过滤为selectedIds(保持与 in 相同的顺序selectedIds)?我希望得到的最终结果:selectedBooks = [    {      "id": 1,      "title": "NPR",      "url": "https://www.npr.org"    },    {      "title": "Google",      "url": "http://www.google.com",      "id": 5    },    {      "title": "Fetch API Docs",      "url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",      "id": 3    }  ]我当前的代码是这样的,但这保留了books数组的顺序(即 [1, 3, 5]):books.filter(function(item) {   return selectedIds.includes(item.id);}
查看完整描述

2 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

往另一个方向走。

 selectedIds.map(id => books.find(b => b.id === id))


查看完整回答
反对 回复 2021-11-12
?
慕妹3242003

TA贡献1824条经验 获得超6个赞

const books = [{

    id: 1,

    title: "NPR",

    url: "https://www.npr.org"

  },

  {

    id: 2,

    title: "Google Docs",

    url: "https://docs.google.com/"

  },

  {

    title: "Fetch API Docs",

    url: "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",

    id: 3

  },

  {

    title: "Yahoo",

    url: "http://www.yahoo.com",

    id: 4

  },

  {

    title: "Google",

    url: "http://www.google.com",

    id: 5

  }

];


const selectedIds = [1, 5, 3];


const mapped = selectedIds.map(id => {

  return books.find(book => book.id === id);

});


console.log(mapped);


查看完整回答
反对 回复 2021-11-12
  • 2 回答
  • 0 关注
  • 209 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号