Extract nested values within objects and arrays, and return the complete type of the original object

I have a dataset that resembles the structure of IconItems:

{
  title: "Category title",
  description: "Example description",
  lists: [
    {
      id: "popular",
      title: "Popular",
      items: [
        {
          id: 1,
          title: "title",
          provider: "provider",
          image: ""
        },
      ....
      ]
    },
    {
      id: "new",
      title: "New",
      items: [
        {
          id: 4,
          title: "studioss2",
          provider: "provider",
          image: ""
        },
       ....
      ]
    } 

I am looking to filter the nested array of items (IconItem type, singular) based on a string value.

For this purpose, I have defined two values:

const filterKeyOpt: Array<keyof IconItem> = ["title", "provider", "image"];
const searchQuery = 'sTudioSS'

I attempted to filter the data with the following function

const logData = () => {
     let filteredData = data?.lists.map((item) => item.items.filter((i) => {
      return filterKeyOpt.some((key) => i[key].toString().toLowerCase().includes(searchQuery.toLowerCase()))
    } /// returns  IconItem[][] | undefined but I want to return type IIconItems | undefined
    ))
console.log(filteredData)
}

However, the output is in the form of

IconItem[][]

I desire the entire object/type. Meaning, filtering based on a nested value and returning a copy of the data object, including matching properties. How can I achieve that?

Playground link

Answer №1

Coding Environment

const dataLogger = () => {
  let a: typeof info = {
    ...info,
    items: info.items.map(item => {
      //                  ^?
      return { 
        ...item,
        details: item.details.filter(detail => {
          //                     ^?
          filterOptions.some((option) => detail[option].toString().toLowerCase().includes(searchText.toLowerCase()))
        })
      }
    }).filter(item => {
      // selecting only relevant items
      return item.details.length
    })
  }
  return a.items.length ? a : undefined;
}

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

Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding? For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09? ...

Is there a way to bring in both a variable and a type from a single file in Typescript?

I have some interfaces and an enum being exported in my implementation file. // types/user.ts export enum LoginStatus { Initial = 0, Authorized = 1, NotAuthorized = 2, } export interface UserState { name: string; loginStatus: LoginStatus; }; ex ...

What is the best way to exclude a particular subtype or property?

Is there a way to exclude a specific nested property? Let's take a look at an example. interface ILikes { article: string, page: string, userId: number | string, } interface IUserData { userName: string, isAdmin: boolean, ...data, ...

Typescript error: the argument passed as type a cannot be assigned to the parameter of type b

In my programming interface, I have defined shapes as follows: type Shape = | Triangle | Rectangle; interface Triangle {...} interface Rectangle {...} function operateFunc(func: (shape: Shape) => void) {...} function testFunction() { const rectFun ...

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Inheritance in Angular with TypeScript Using Generic Types

Looking for some assistance from the angular2 / typescript experts out there to guide me in the right direction before I lose my mind :-) Here's what I'm trying to achieve: I want to create a parent class that implements its own defined parent ...

Angular2, multi-functional overlay element that can be integrated with all components throughout the application

These are the two components I have: overlay @Component({ selector: 'overlay', template: '<div class="check"><ng-content></ng-content></div>' }) export class Overlay { save(params) { //bunch ...

Alert the parent angular component of any changes in the object

I am working with a large object in my component, where the properties of the object are connected to various components and inputs within the template: constructor() { this.data = { identifier: null, isRequired: true, title: ' ...

What are the reasons for discouraging the use of canActivate always returning false?

I've searched extensively to avoid duplicate postings and tried various solutions, but unfortunately, none of them have resolved the issue. My implementation of canActivate to secure a dashboard seems to be working properly, but it's always retu ...

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

Issue arose following the update from Angular 5 to 6, impacting the VSTS build process

Upon upgrading from Angular 5 to 6, I successfully got it running locally. It builds and compiles with --prod. Integration into an .NET MVC application went smoothly. However, when the build on VSTS is triggered, a series of errors surface: node_modules&b ...

How can I inform Typescript that an interface will exclusively consist of defined members?

My interface looks like this interface Person { name?:string; age? :number; gender?:string } I need to reuse the same interface type, but with a modification indicating that all members will never be undefined. The updated version would look like this: ...

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...

Directly mapping packages to Typescript source code in the package.json files of a monorepo

How can I properly configure the package.json file in an npm monorepo to ensure that locally referenced packages resolve directly to their .ts files for IDE and build tooling compatibility (such as vscode, tsx, ts-node, vite, jest, tsc, etc.)? I want to a ...

Encountering issues with accessing properties of undefined while chaining methods

When comparing lists using an extension method that calls a comparer, I encountered an error. Here is the code snippet: type HasDiff<T> = (object: T, row: any) => boolean; export const isListEqualToRows = <T>(objects: T[], rows: any[], has ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

Utilizing typescript to isolate specific functionality from a class without extending it

Imagine a scenario where I have a class with different areas of functionality: export class TreeTable extends someOtherClass { constructor(){ super.constructor(); } //========= area 1 of functionality ==== itemRightClick(){this.contex ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Using TypeScript to determine the week number - the value on the right side of the math operation must be of data type 'any'

I've spent a lot of time searching for code to help me calculate the week number in my Angular app according to ISO standards. It's been challenging to find JavaScript-specific code, but I believe I may have found something - however, I encounter ...