首页 > 解决方案 > 如何使用 Javascript 快速搜索 JSON?

问题描述

我有一个词形还原嵌套字典,比如

{
{"abbreviate": ["abbreviated","abbreviates","abbreviating"]},
{"abdicate": ["abdicated","abdicates","abdicating"]}
}

我想快速搜索值以获取相应的键(查找abbreviated→输出abbreviate)。Fast- 因为文件大约 6MB。这个搜索将在 Chrome 扩展中使用,所以我更喜欢 Javascript,而不是 Python。

完成这种搜索的技术是什么?

标签: javascriptjson

解决方案


在我看来,您需要将对象转换为用于快速哈希搜索的表单:

{
    abbreviated: 'abbreviate',
    abbreviates: 'abbreviate',
    abbreviating: 'abbreviate',
    abdicated: 'abdicate',
    abdicates: 'abdicate',
    abdicating: 'abdicate',
};

const data = {
    abbreviate: ['abbreviated', 'abbreviates', 'abbreviating'],
    abdicate: ['abdicated', 'abdicates', 'abdicating'],
};

const dictionary = Object.keys(data).reduce((dict, key) => {
    const records = data[key];
    const obj = records.reduce((acc, val) => ({ ...acc, [val]: key }), {});

    return { ...dict, ...obj };
}, {});

console.log(dictionary['abbreviated']);


推荐阅读