如何有效创建相似对象的数组?

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

我有一系列类似的对象,如下所示:

const urls = [
    {
        title: "title 1",
        url: "https://example.com/1" 
    },
    {
        title: "title 2",
        url: "https://example.com/2" 
    },
    ...
] 

为了减少重复,我想到了做一个类:

class URL {
    title: string
    url: string
   
    constructor(title:string, url:string) {
        this.title = title
        this.url = url
    } 
} 

const link1 = new URL("title 1", "https://example.com/1")
const link2 = new URL("title 2", "https://example.com/2")

这有两个缺点:

  • 我必须分配未使用的变量名称
  • 创建它们的数组似乎会导致内存泄漏

有更好的方法吗?我的目标是在数组上运行过滤器(输入特定的

title
,输出其对应的
url
)。

javascript arrays class filter
2个回答
2
投票

根据您的描述,您真正想要的只是使用标题来获取 URL 的查找。

您根本不应该为此使用数组。最好使用

Map
或 JS 对象,因为它们是为查找而设计的,因此可以非常快地完成它们。 e.次线性。

来自 MDN 文档

该规范要求实现映射“平均而言,提供与集合中元素数量呈次线性关系的访问时间”。因此,它可以在内部表示为哈希表(具有 O(1) 查找)、搜索树(具有 O(log(N)) 查找)或任何其他数据结构,只要复杂度优于 O (N).

使用 JavaScript 对象

const urls = {
  "title 1": "https://example.com/1",
  "title 2": "https://example.com/2",
};
console.log(urls["title 1"]);
console.log(urls["Non-existing title"] ?? "No URL found for this title");

带着
Map

const urlMap = new Map();
urlMap.set("title 1", "https://example.com/1");
urlMap.set("title 2", "https://example.com/2");

console.log(urlMap.get("title 1"));
console.log(urlMap.get("Non-existing title") ?? "No URL found for this title");

按照特定模式按标题查找 URL

如果您的标题遵循特定模式,并且您希望明智地处理事情,而不是不必要地浪费存储空间,您也可以执行以下操作:

  • 解析标题以获得查找密钥和标题中编码的其他信息
  • 使用标题查找基本URL
  • 使用标题中编码的其他信息来调整 URL(路径参数、搜索参数等)

这是一个基于您的示例的非常简单的示例。根据标题和 URL 的复杂程度,这可能会变得更加复杂。

const urls = {
  title: new URL("https://example.com"),
  anothertitle: new URL("https://anothertitle.net")
};

/**
 * Gets a URL with parameter for a title with a specific format.
 * @param {string} title title
 * @returns {URL} Url
 */
function getUrlForTitle(title) {
  const [key, pathValue] = title.split(" "); // you could of course use some Regex here and throw an error if it doesn't match
  const url = urls[key];
  if (url === undefined) throw new Error(`No URL found for title '${title}'`);
  url.pathname = `/${pathValue}`;
  return url;
}

console.log(getUrlForTitle("title 1").toString());
console.log(getUrlForTitle("title 2").toString());
console.log(getUrlForTitle("title 12").toString());
console.log(getUrlForTitle("anothertitle 145").toString());
// errors
console.log(getUrlForTitle("unknowntitle 145").toString());
/* Stackoverflow: show only console */
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}


0
投票

如果您的目标是根据标题过滤数组并检索相应的 URL,则无需创建类的实例即可实现它。您可以使用对象或 Map 将标题存储为键,将其相应的 URL 存储为值。具体方法如下:

const urls = [
    {
        title: "title 1",
        url: "https://example.com/1" 
    },
    {
        title: "title 2",
        url: "https://example.com/2" 
    },   
];

const urlsMap = new Map(urls.map(item => [item.title, item.url]));

const getUrlByTitle = (title) => {
    return urlsMap.get(title) || null; 
};

const titleToSearch = "title 1";
const url = getUrlByTitle(titleToSearch);
if (url) {
    console.log(`URL for ${titleToSearch}: ${url}`);
} else {
    console.log(`No URL found for ${titleToSearch}`);
}

在此方法中:

  • 您将 URL 定义为对象中的键值对 (
    urls
    )。
  • getUrlByTitle
    函数将标题作为输入,并从
    urls
    对象返回相应的URL。
  • 如果在
    urls
    对象中找到标题,则返回对应的URL;否则,返回
    null

这种方法消除了创建类实例的需要,并避免了内存开销。也简化了代码,更加简洁。

© www.soinside.com 2019 - 2024. All rights reserved.