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

问题描述 投票:1回答:2

这里是书籍对象的数组。

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,如何将books数组仅过滤到selectedIds(与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);
}
javascript arrays
2个回答
3
投票

朝另一个方向前进。

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

1
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.