Searching through a json object using typescript

While attempting to retrieve JSON data from a URL, I encountered a particular issue.

The problem lies in the fact that each row in the Datarows array contains 5 rows, each row consisting of 47 cells. Out of these 47 cells in each row, I am specifically interested in just two of them:

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

So, my query is: How can I extract only the 2 cells I am interested in from each row?

The format for a cell is as follows:

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

Below is my current implementation:

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"];

Ultimately, I aim to achieve a result that appears as follows, where cell X represents the title cell, and cell X+1 indicates the path cell:

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

Answer №1

I've devised a simple and organized approach for this task. By breaking down the process into two separate functions, we achieve modularity.

const myStrings: string[] = Datarows
    .map(getDetails) // extracting relevant information
    .map(formatString);     // formatting the information

// if necessary, ValueType can also be returned
type Details = {title: string, path: string};

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

    // error handling in case Title or Path cell is not found
    if (titleCell === undefined || pathCell === undefined)
        throw new Error('');

    // if necessary, ValueType can also be returned
    return {title: titleCell.value, path: pathCell.value};
}

// Simple string interpolation for formatting the result
function formatString(details: Details, rowIndex: number) {
    return `Row ${rowIndex}: ${details.title}, ${details.path}`;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to customize a React component using TypeScript?

Let's say I have a functional component like this: function MyComp({a, b, c, d, e, f}: any) { ... } Is there a way to create a specialized version of this component where I provide values for "a" and "b," but allow other users to choose the r ...

Passing props from parent component to map function in ReactJS results in undefined props

In my project, I dynamically create <textarea> elements using the map() function. Each textarea should have a unique value when the component is rendered. // Within the render method of ComponentA fruits.map((fruit) => { return <textarea na ...

Code for a regular expression that permits either letters or numbers with symbols

Here is the code snippet I am using for data validation in jQuery: return /^(?=.*[A-Za-z0-9/\$#.-_])[A-Za-z0-9/\$#.-_]$/i.test(value) The requirement is that the value should begin with letters or numbers, or a combination of both. Afterwards, ...

Edit esri pop-up template

Can I customize the popupTemplate in Esri to match my design? I currently have a popupTemplate set up like this: popupTemplate: { content: [{ type: "fields", fieldInfos: [{ fieldName: "Name" ...

What is the best way to create a "check all" feature in React using child components?

I have come across a few questions here that somewhat address the issue, select all managed state of controlled checkboxes but none of them provide a solution for rendering a component with a checkbox. What I want is something like this, render: funct ...

Button's focus event doesn't trigger on iPad

I am facing an issue with adding a bootstrap popover to my website. The popover should appear when the user clicks a button using the focus event. This functionality works fine on desktop browsers, but on the iPad, it seems like Safari on iOS does not trig ...

Using Angular's $q service in the run block

I have a scenario where I need to load data from local files using the global loadJSON function (though it's not mandatory, it's recommended). Once the data is loaded from all the documents, I want to print the string 'i ve loaded'. T ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Determining the optimal number of rows and columns based on an integer value

Here's a brain teaser for you: /** * Let's figure out the optimal number of rows and columns for your garden to be as square as possible, based on the number of seeds you have. * * @param {number} seedCount - The total number of seeds in you ...

What is preventing JSFiddle from displaying this object?

I'm currently experimenting with objects in Angular. While using JSFiddle to define some JSON objects in an Angular controller, I've encountered a problem - it's not working and I can't seem to figure out why. Can someone with fresh ey ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

Incorporating timed hover effects in React applications

Take a look at the codesandbox example I'm currently working on implementing a modal that appears after a delay when hovering over a specific div. However, I've encountered some challenges. For instance, if the timeout is set to 1000ms and you h ...

Notify when the button value changes to "submit"

I recently added a jQuery form wizard to my website. I want users to receive an alert in JavaScript when they reach the end of the form. To achieve this, I inserted a simple JavaScript code at the beginning of my page within <head>..some code</hea ...

Error: JSDOM - The document variable has not been declared

After creating a basic webpage that displays a single message, I decided to experiment with JSDOM and encountered an error. Despite researching online examples and Stack Overflow questions, I have struggled to resolve even the most straightforward scenario ...

javascript box is hidden to prevent displaying of values

I need the negative character to disappear when the user clicks the minus (-) button. The count should stop at 0. Currently, it is displaying characters like -1, -2, -3. I only want to show 0 or numbers greater than 0. <script type="text/javascript" ...

Guide on creating a function that accepts an Array of strings as a parameter and displays the initial letter of each element individually on separate lines

I am currently tackling my initial JavaScript assignment which involves the task of creating a function that accepts an array of strings as its parameter and outputs the first letter of each element individually on separate lines. The unique requirement ...

Encountering a 404 error while using THREE.ImageUtils.loadTexture in three.js

My first attempt at using three.js involves loading a 3D model, but I'm encountering an issue with texture loading. loader.load('models/asteroid_OBJ/asteroid OBJ.js', function (geometry, materials) { var material = new THREE.MeshLambertM ...

Automated resizing for various monitor dimensions in HTML

Is there a way to dynamically adjust the zoom level on an HTML webpage based on the monitor size? For instance, an image that appears large on a laptop screen may look small on a PC monitor. Is there a solution available to scale the picture size as the mo ...

Guide to initializing the state in pinia with Typescript

I am encountering an issue while trying to add typescript to a pinia store. Any suggestions on how to resolve this problem would be appreciated. The project currently utilizes pinia:^2.0.16 and Vue:3.2.37 The error message is as follows: Type '{}&a ...

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...