Retrieve the non-empty attributes of a JSON object

I have a function in Typescript that extracts specific values from a JSON data object, some of which may be empty. How can I retrieve only certain data fields?

Here is the function:

let datosCod;
    for (let get in Object.keys(transfConsData)) {
      const value = transfConsData[get];
      if (value.Country === 'Colombia') {
        datosCod = value;
      }
    }

This is what the variable dataCod contains:

{ Country: 'Colombia',
  Ser: '',
  Ins: 'blue',
  BBDD: ''}

My objective is to extract the following information:

{ Country: 'Colombia',
  Ins: 'blue'}

totalValues = 2

Answer №1

Here is the solution:

const info = { City: "Tokyo", Population: "", Language: "Japanese", Currency: "" };
const cleanInfo = Object.fromEntries(
  Object.entries(info).filter(([_, value]) => !!value)
);

console.log(cleanInfo);
// result: Object { City: "Tokyo", Language: "Japanese" }

The crucial step is the filtering process. The line

.filter(([_, value]) => !!value)
effectively removes any false values, including null and empty strings. If you only want to filter out empty strings, you can use
.filter(([_, value]) => value !== '')
instead. However, it seems like your goal is to eliminate all falsy values.

Another approach without using fromEntries involves reduce:

const info = { City: "Tokyo", Population: "", Language: "Japanese", Currency: "" };
const cleanInfo = Object.entries(info)
  .filter(([_, value]) => !!value)
  .reduce((accumulator, [key, value]) => {
    accumulator[key] = value;
    return accumulator;
  }, {});

console.log(cleanInfo);
// result: Object { City: "Tokyo", Language: "Japanese" }

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

Is there a way to set up an HTTP service in Orbeon by utilizing HTTP parameters and extracting data from a JSON response?

Currently, I am exploring the potential of Orbeon for creating forms within my application. This particular application makes use of HTTP web services by passing and receiving JSON data through HTTP parameters. I would like to know how I can set up Orbeon ...

Grabbing data using @RequestParam and $http.post in angularjs I will

I need help sending an array arr=["xxx.yyy","zzz.vvv"] over to a spring endpoint in this manner: $http.post("url",arr) On the spring side, I have the following setup: @PostMapping(value = "url") public Set<String> func(@RequestParam(name="ar ...

Creating a JSON Object from Query Result in SQL Server

I'm currently working with Azure SQL Server and attempting to export the results of a query in a specific format. Desired Query Result: { "results": [{...},{...}], "response": 0 } Reference Example: https://msdn.microsoft.com/en-us/library/dn9218 ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

What is the best way to validate an Array, ensuring that the test fails only if there is no match found among all the values that were

I'm currently working on a test with the NightwatchJs framework where I need to compare an actual value against a set of valid values. However, my current approach is resulting in multiple failures even though the correct value exists in the expected ...

Discovering a random element within a PHP array

A challenging task is before me as I examine the array and its var_dump result: array 6 => int 7 7 => int 8 9 => int 10 11 => int 12 Intriguingly, I aim to extract a random number from this array using $avil=array_r ...

Tips for expanding Jackson property detection in a universal manner for all types?

After discussing serialization in my previous post, I am now looking to expand my support to include the JsonFormatVisitor. My requirements remain the same: I have objects of various types (interfaces). The type of these objects is unknown beforehand. I ...

Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab. This is my userlog.component.ts file: import { Component, OnInit, O ...

When transferring JSON to JavaScript within Laravel, the JSON data gets converted into HTML entities by JavaScript

Within my Laravel controller, I am constructing a multidimensional associative array: $trendChart = Array ( "series" => Array ( "data" => Array(1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5) ), "xaxis" => Arr ...

Ensuring seamless collaboration between Typescript node modules

Is there anyone who has successfully set up a configuration where module 1, using TypeScript, is referencing another module 2 also with TypeScript, and both are utilizing tsd types like node.d.ts? I have been able to compile and use both modules without a ...

Saving JSON output to CSV in Bash

I've been working on a bash script where I'm attempting to save the output of an aws command (which is in JSON format) to a CSV file. The JSON output is from running the aws s3 command. { "Expiration": { "Days": 7 }, ...

"Encountering a Python JSON TypeError while attempting to parse data from

I am relatively new to python and stumbled upon an example that almost fits my needs, but I am encountering errors while trying to parse data from a GET request response. The specific error message I keep facing is: "activity['parameters'][& ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

What causes the distinction between entities when accessing objects through TestingModule.get() and EntityManager in NestJS?

Issue: When using TestingModule.get() in NestJS, why do objects retrieved from getEntityManagerToken() and getRepositoryToken() refer to different entities? Explanation: The object obtained with getEntityManagerToken() represents an unmocked EntityManag ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

Executing a child component function once the parent component data is loaded in Angular 5

In my project, I have a parent component called program-page.component where I am invoking a function to fetch some data. ngOnInit() { this.getProgress(); } getFirstProgramItem() { this._contentfulService.getProgramItem(4, 1) .then((programItem) = ...

Calculating the mean of each column in a two-dimensional array

I have a task where I need to calculate the average of all columns in a 2D array and then store them in a 1D array. From this 1D array, my goal is to identify the position of the lowest number. Although the code I currently have does not produce any comp ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

PHP: Check if an array contains values that begin with a specific value

I've created a function designed to search through an array and find values that start with the specified second parameter: public static function arrayContainsValueStartingBy($haystack, $needle) { $len = strlen($needle); foreach ($hays ...

What could be causing the data retrieved from the JSON action to appear as "undefined"?

Have you examined the console.log() outputs and table structure for correctness? I suspect an error in one of them. I am fetching data from the database and using console.log() to display both the data in the loadData() function and value in the $.each(). ...