JavaScript 實現通過 id 數組獲取可展示的 name 拼接字符串
場景
有一個包含許多對象的數組,每個對象都包含了一個標識(id)和一個名稱(name)。想要從這個數組中選出特定的一些對象,這些對象的標識(id)在另一個數組中已經給出。然後,想把這些選出來的對象的名稱(name)連接成一個字符串,用逗號分隔起來,以便進一步處理或顯示。
代碼實現
實現方式一
可以使用 JavaScript 中的 Array 的 filter()
和 map()
方法來實現這個功能。以下是一個示例代碼:
// 假設你有一個包含 JSON 對象數組的變量
const jsonArray = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Doe" },
];
// 假設你有一個 id 數組
const idArray = [1, 3];
// 使用 filter() 方法篩選出符合 id 數組中的 id 的對象,然後用 map() 方法獲取對應的 name 屬性
const filteredNames = jsonArray
.filter((obj) => idArray.includes(obj.id))
.map((obj) => obj.name);
// 使用 join() 方法將 name 組合成字符串,以 , 分隔
const result = filteredNames.join(", ");
// 輸出結果
console.log(result); // 輸出: John, Doe
這個代碼首先使用 filter()
方法從 jsonArray
中篩選出符合 idArray
中 id 的對象,然後使用 map()
方法將這些對象轉換爲對應的 name
屬性的數組。最後,使用 join()
方法將數組中的 name
以 ,
分隔成一個字符串。
實現方式二
當使用 find()
方法查找數組中的對象時,它會返回第一個滿足條件的元素。而 map()
方法會創建一個新數組,其中的元素是原始數組元素調用某個方法後的返回值。
下面是如何使用 find()
和 map()
方法來實現你的場景:
// 假設你有一個包含 JSON 對象數組的變量
const jsonArray = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Doe" },
];
// 假設你有一個 id 數組
const idArray = [1, 3];
// 使用 map() 方法將 id 數組中的每個 id 對應的 name 找出來
const filteredNames = idArray.map((id) => {
// 使用 find() 方法查找滿足條件的對象
const foundObject = jsonArray.find((obj) => obj.id === id);
// 如果找到了對象,則返回其 name 屬性;否則返回空字符串
return foundObject ? foundObject.name : "";
});
// 使用 join() 方法將 name 組合成字符串,以 , 分隔
const result = filteredNames.join(", ");
// 輸出結果
console.log(result); // 輸出: John, Doe
在這個示例中,map()
方法用於遍歷 idArray
數組中的每個元素,並使用 find()
方法在 jsonArray
中查找與當前 id
匹配的對象。如果找到了匹配的對象,則返回它的 name
屬性;否則返回空字符串。最後,使用 join()
方法將 filteredNames
數組中的元素用逗號連接成一個字符串。