【问题标题】:Querying a json object in typescript在打字稿中查询 json 对象
【发布时间】:2018-07-23 23:21:07
【问题描述】:

最近我在从 url 获取一些 json 数据时偶然发现了一个问题。

我的问题是 Datarows 包含 5 行,每行包含 47 个单元格。 在每行的 47 个单元格中,我只对其中两个感兴趣:

  Cell with Key = "Title"
  Cell with Key = "Path"

所以我的问题是:如何在每一行中只查询我感兴趣的 2 个单元格?

一个单元格的界面是这样的:

Key: string;
value: string;
ValueType: string;

这是我的实现

let queryUrl = "/_api/search/query?querytext='" + encodeURIComponent(searchValue) + "'&rowlimit=5";
let response = await this.props.context.spHttpClient.get(queryUrl, SPHttpClient.configurations.v1.overrideWith(spSearchConfig));
let obj = await response.json();
let Datarows = obj["PrimaryQueryResult"]["RelevantResults"]["Table"]["Rows"];

我的最终结果应该类似于: 其中单元格X是标题单元格,单元格X+1是路径单元格

Row 0: Cell0, Cell1
Row 1: Cell0, Cell1
Row 2: Cell0, Cell1
Row 3: Cell0, Cell1
Row 4: Cell0, Cell1

【问题讨论】:

标签: javascript json typescript


【解决方案1】:

这是一个非常简单的方法。我将整个事情分解成两个模块化功能。

const myStrings: string[] = Datarows
    .map(getInterestingDetails) // first extract useful info
    .map(formResultString);     // then use the info

// if needed, you can also return ValueType
type InterestingDetails = {title: string, path: string};

function getInterestingDetails(row: DataRow): InterestingDetails {
    const titleCell= row.cells.find((cell: Cell) => cell.Key === 'Title');
    const pathCell= row.cells.find((cell: Cell) => cell.Key === 'Path');

    // here you could handle the case when the cell 
    // with Key = "Title" or "Path" is not found
    if (titleCell === undefined || pathCell === undefined)
        throw new Error('');

    // if needed, you can also return ValueType
    return {title: titleCell.value, path: pathCell.value};
}

// Just some string interpolation, nothing interesting here
function formResultString(details: InterestingDetails, rowIndex: number) {
    return `Row ${rowIndex}: ${details.title}, ${details.path}`;
}

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2021-01-26
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2020-12-24
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多