Avoid including any null or undefined values within a JSON object in order to successfully utilize the Object.keys function

My JSON data structure appears as follows:

{
'total_count': 6,
'incomplete_results': false,
'items': [
  {
    'url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2',
    'repository_url': 'https://api.github.com/repos/Samhot/GenIHM',
    'comments_url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2/comments',
    'events_url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2/events',
    'html_url': 'https://github.com/Samhot/GenIHM/issues/2',
    'id': 293234257,
    'number': 2,
    'title': 'Create server for RESTful API',
    'user': {
      'login': 'Samhot',
      'id': 7148311,
      'avatar_url': 'https://avatars3.githubusercontent.com/u/7148311?v=4',
      'gravatar_id': '',
      'url': 'https://api.github.com/users/Samhot',
      'html_url': 'https://github.com/Samhot',
      'followers_url': 'https://api.github.com/users/Samhot/followers',
      'subscriptions_url': 'https://api.github.com/users/Samhot/subscriptions',
      'organizations_url': 'https://api.github.com/users/Samhot/orgs',
      'repos_url': 'https://api.github.com/users/Samhot/repos',
      'received_events_url': 'https://api.github.com/users/Samhot/received_events',
      'type': 'User',
      'site_admin': false
    },
    'state': 'open',
    'locked': false,
    'assignee': null,
  }
 ]
};

I am attempting to extract all the keys from this JSON using the getDeepKeys() function :

getDeepKeys2(obj) {
  const keys = Object.keys(obj);
  const childKeys = keys
    .map(key => obj[key])
    .map(
      value =>
        Array.isArray(value)
          ? this.getDeepKeys2(value[0]) : typeof value === 'object'
            ? this.getDeepKeys2(value) : []
    )
    .reduce((acc, keys) => [...acc, ...keys], []);
  this.dispotest = [...keys, ...childKeys];
  return this.dispotest;
}

This method functions flawlessly unless the JSON includes a null or undefined value like 'assignee': null.

If such a value is present in my JSON, the function will result in:

ERROR TypeError: Cannot convert undefined or null to object

I am considering utilizing the typeof function by implementing

if (typeof value === null { return null; }
but I am unsure about where to incorporate this...

Any assistance will be greatly appreciated! Thank you!

Answer №1

It seems like your initial code:

if (typeof value === null { return null; }

Simply needs to be revised as follows:

if (value == null) { return null; }

Note: the double == is intentional as it covers both null and undefined cases.

Complete Example:

function getDeepKeys2(obj) {
  const keys = Object.keys(obj);
  const childKeys = keys
    .map(key => obj[key])
    .map(value => {
      if (value == null || (value.length != null && value.length === 0)) {
        return null;
      }
      return Array.isArray(value)
        ? this.getDeepKeys2(value[0]) : typeof value === 'object'
        ? this.getDeepKeys2(value) : []
    })
    .reduce((acc, keys) => [...acc, ...keys], []);
  this.dispotest = [...keys, ...childKeys];
  return this.dispotest;
}

Output (in console):

(29) […]
0: "total_count"
1: "incomplete_results"
2: "items"
3: "url"
4: "repository_url"
5: "comments_url"
6: "events_url"
7: "html_url"
8: "id"
9: "number"
10: "title"
11: "user"
12: "state"
13: "locked"
14: "assignee"
15: "login"
16: "id"
17: "avatar_url"
18: "gravatar_id"
19: "url"
20: "html_url"
21: "followers_url"
22: "subscriptions_url"
23: "organizations_url"
24: "repos_url"
25: "received_events_url"
26: "type"
27: "site_admin"
28: null
length: 29
__proto__: Array []

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

Tips for selecting a specific item in a list using onClick while iterating through a JSON array in React

I have a unique JSON file filled with an array of objects, each containing a "Question" and "Answer" pair (I am working on creating an FAQ section). My current task involves mapping through this array to display the list of questions, a process that is fun ...

Incorporate matter-js into your TypeScript project

Upon discovering this file: https://www.npmjs.com/package/@types/matter-js I ran the following line of code: npm install --save @types/matter-js When I tried to use it in the main ts file, an error message appeared: 'Matter' refers to a U ...

An error occurred in the SessionsController#create method while attempting to authenticate a user from the Twitter API with omniauth

While attempting to implement Twitter sign-in for users, I encountered an error in the SessionsController. The issue occurs upon redirection to for user authentication. Instead of being redirected to the "Authorize App" page on Twitter after authenticatio ...

Personalize the JSON within the pipeline expression builder of Azure Data Factory (ADF)

Within ADF, there exists a variable containing the following value. @json(concat('{','"S.No":',variables('counter'),',"Input Table":"Input TblName","Output Table":"[Tbl1, tbl2, ...

What is preventing access to the JSON data?

function loadResponse(filter) { $.ajax({ type: 'GET', url: 'path/to/example.json', dataType: 'json', cache: false, beforeSend: function () { console.log('load ...

Discovering a specific value within a JSON stringified array

I am looking for a specific value within a JSON stringify array [{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":" ...

Any idea how to resolve this typescript typing issue: "The argument, either a string or number, cannot be assigned to the parameter of type 'SetStateAction<string>'"?

Just recently delving into TypeScript, I've encountered a persistent typing problem that has proven challenging to resolve despite numerous attempts. The error message causing me trouble reads as follows: Argument of type 'string | number' ...

Maintain Angular Dropdown Menu Open Across Page Refresh

I am currently working on an HTML/Typescript view that is connected to a SQL Database. Whenever there are changes made to the database, the entire webpage reloads. The issue we are facing is that we have dropdown menus on the page that clients want to rema ...

Using Typescript: Utilizing only specific fields of an object while preserving the original object

I have a straightforward function that works with an array of objects. The function specifically targets the status field and disregards all other fields within the objects. export const filterActiveAccounts = ({ accounts, }: { accounts: Array<{ sta ...

Converting intricate HTML table data into JSON format with the help of jQuery

Looking to extract JSON data from selected rows in the HTML table below using jQuery. The JSON output should include any user-entered comments from the textboxes. Any guidance or suggestions would be greatly appreciated. <table id="potable_grid" class ...

"When a class extends another class and utilizes properties within a static property, it essentially becomes

I have been encountering challenges with generics in TypeScript for quite some time now. My current setup is as follows: First, there is a generic class defined as: class Entity { public static schema = {}; } Then, there is a class that extends the ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Incorporate a JavaScript array into a TypeScript document

Having a file named array.js with a large collection of strings, structured like this: module.exports = ["word1","word2",...] I attempted to utilize this array in my validation.ts file by adding the following line: let wiki = require('./array.js&a ...

How to extract JSON data from within an Array using JMeter

Can someone please help me with extracting the value USDT from the provided sample response? I currently use JSON Path tester $..currency[0] method for extraction, but I want to make it more flexible without specifying a number. Is there a way to achieve t ...

The object is classified as 'undetermined' (2571) upon implementation of map() function

Despite conducting a thorough search about this error online, I still haven't been able to find a solution. Let's jump into an example with data that looks like this: const earthData = { distanceFromSun: 149280000, continents: { asia: {a ...

Tips for Extracting Data from JSON String in Automation Anywhere after Making a REST API Request

Can someone guide me on how to extract "item" details from the "searchResult" element in Automation Anywhere? I'm struggling with parsing a JSON string that was returned as part of a REST API call, and unlike UiPath, AA doesn't seem to provide an ...

TypeScript focuses on checking the type of variables rather than their instance

Is there a way to pass a type (not an instance) as a parameter, with the condition that the type must be an extension of a specific base type? For example abstract class Shape { } class Circle extends Shape { } class Rectangle extends Shape { } class ...

The component is expected to return a JSX.Element, however it is failing to return any value

The issue lies with this component: const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => { props.map((item, index) => { return <a href={item.href} key={index}>{item.name}</a> }) }; export default Naviga ...

The TypeError encountered in an Ionic pipe states that the property 'toString' cannot be read as it is undefined

I have a news application built in Ionic 4. The pubDate property of the UutinenPage class is being asynchronously assigned a value of data.items[this.id].pubDate in the uutinen.page.ts file. The expected format of this value is something like 2019-02-19 04 ...

The promise callback in Angular2 is unable to access this

This snippet of code is quite odd, but it resides within a service context: constructor() { gapi.load('client:auth2', this.loadGoogleApi); } private loadGoogleApi() { // Array of API discovery doc URLs for APIs used by the quickstart ...