在typescript中查询json对象

时间:2018-02-13 14:41:44

标签: javascript json typescript

最近我偶然发现了一个问题,同时从网址获取了一些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

1 个答案:

答案 0 :(得分:0)

这是一种非常直接的方式。我将整个事情分解为两个模块化功能。

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}`;
}