Discovering numbers within a JSON object and extracting them - a step-by-step guide

If I have a JSON object coming from a random dataset and want to search through it to manipulate the number values, how can I achieve this? Looping through the object using for...of allows me to get the keys, but I'm unsure how to access every key-value pair and return the numbers specifically. Here is an example:

var obj = {
  "a0": {
    "count": 41,
    "name": "Park",

  },
  "a1": {
    "count": 52,
    "name": "Greg",

  },

  "a2": {
    "count": 150,
    "name": "Sylvain",

  },
  "a3": {
    "count": 276,
    "name": "Macho",

  },
  "a4": {
    "count": 36,
    "name": "Mariam",

  },
  "a5": {
    "count": 39,
    "name": "Blanca",

  }

}

Looping through can be done like this:

for (let i of Object.keys(obj)) {
  console.log(obj[i]);
}

While there are properties like hasOwnProperty and keys on the Object, they don't directly provide values. Accessing count by doing obj[i].count works, but checking if count exists beforehand is needed. A more generic approach is sought for extracting numeric values in an array or performing manipulations with them.

Edit: This query is focused on extracting properties with numeric values within the object.

Any assistance would be appreciated.

Thanks a lot.

Answer №1

To extract only properties with numeric values from an object, you can utilize the `Object.keys()`, `Array.map()`, and `Array.reduce()` methods in JavaScript:

First, here's how you can achieve this by iterating over the keys of the object and filtering out non-numeric values:

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.keys(obj).map((key) => {
  const o = obj[key];
  
  return Object.keys(o).reduce((r, k) => typeof o[k] === 'number' ?
    {...r, [k]: o[k]} : r , {});
});

console.log(result);

You can also simplify the process using `Object.values()` and `Object.entries()` if supported by the browser:

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.values(obj).map((o) =>
  Object.entries(o).reduce((r, [k, v]) => typeof v === 'number' ?
    {...r, [k]: v} : r)
);

console.log(result);

If your target browser supports `Object.fromEntries()`, you can further streamline the process by filtering out non-numeric values and converting back to an object:

const obj = {"a0":{"count":41, "demo": 15, "name":"Park"},"a1":{"count":52, "demo": 53, "name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

const result = Object.values(obj)
  .map((o) => Object.fromEntries(
    Object
      .entries(o)
      .filter(([,v]) => typeof v === 'number')
  ))

console.log(result);

Answer №2

const data = {"a0":{"count":41,"name":"Park"},"a1":{"count":52,"name":"Greg"},"a2":{"count":150,"name":"Sylvain"},"a3":{"count":276,"name":"Macho"},"a4":{"count":36,"name":"Mariam"},"a5":{"count":39,"name":"Blanca"}};

var numbersArray = [];
for (var prop in data) {
numbersArray.push(data[prop].count)
}
console.log(numbersArray);

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

Differentiating Typescript will discard attributes that do not adhere to an Interface

Currently, I am working with an API controller that requires a body parameter as shown below: insertUser(@Body() user: IUser) {} The problem I'm facing is that I can submit an object that includes additional properties not specified in the IUser int ...

Python 3 loop malfunctioning

Recently, I've been delving into Python and conducting some experiments. At home, I have a weather station connected to a JSON Web API. My goal is to use Python to display the temperature on a screen. However, I'm encountering an issue where the ...

Identify the absence of search results in an Ajax request to the search page before rendering the HTML content

I am attempting to retrieve JSON code from a page using the following PHP function: private function __ajax_admin_search($username = '') { $result = $this->admin_login->Admin_Username_Ajax($username); $count = count($result); for ...

What is the process for inserting a new item into a mongoose array?

I'm currently developing a confidential web application. Below is the layout I've created for the user. const itemsSchema = { name: String } const userSchema = new mongoose.Schema({ username: String, email: String, password: String, M ...

JavaScript redirecting without refreshing the page

Currently, I am faced with a dilemma involving an Ajax function that calls a remote site, saves data to a database, and then needs to refresh the current page to display the new information. The complication arises from the fact that tabs are being utilize ...

How can you integrate jquery ajax in WordPress?

Recently, I started learning about jquery and have been following a tutorial on creating instant search using jquery. The tutorial can be found here. Now, I am trying to implement this on my WordPress site, but it seems like things work differently when d ...

Enable direct download from external servers

I'm in search of a way to prompt a download (by right-clicking and selecting "save as") for both mp4 and flv files. The challenge is that these files are not hosted on my server, they are direct links from external websites. I have tried using .htacce ...

Decoding a solitary element within an array

How can I unmarshal JSON arrays into single objects in Go? For instance, consider a JSON response retrieved from an API endpoint: { "results": [ { "key": "value" } ] } In my Go code, I have defined a struct to represent the object in ...

retrieving data from Redis with the help of Node.js

I'm having trouble with the code snippet below. Despite setting values for the left_label and right_label variables in Redis, they always seem to return as "true". I suspect this is due to the client.get function returning true when successful. How ca ...

Struggling to achieve the expected results when trying to convert a PHP array into JSON

When I receive names and links of files from an external website, I use the following code to convert them into a JSON string: <?php include('simple_html_dom.php'); $f = $_GET['f']; $w = "www.something.com"; $dom = file_get_html($w ...

Storing approximately 1 kilobyte of information throughout various pages

Is it feasible to store approximately 1kb of data while transitioning between two pages on the same domain using Javascript, Jquery (1.7), and Ajax? For instance, a user inputs data into a textbox on one page and then moves to another specific page. Can ...

getting information from a JSON array using AngularJS

Looking to extract all images from the imagePath array in the following JSON. While retrieving a single image works fine, encountering difficulties when trying to fetch the entire imagePath array. Any help with this issue would be greatly appreciated. Than ...

How can I achieve jq to output decimal notation instead of scientific notation when using tonumber()?

When handling a JSON object with the string "0.0000086900" as a key-value pair, performing |tonumber on it returns 8.69e-06. How do I ensure that only decimals are consistently returned? In this scenario, it should be 0.0000086900 SOLUTION (adapted from ...

Can file input buttons be custom styled?

Since I am using Material-UI, the traditional methods are not working for me. I have a form with two buttons positioned next to each other. One button is an "Upload File" input for users to upload a file, and the other is a submit button. I want both butto ...

Transmit JSON data to a node.js server

Currently, I am in the process of developing an application that involves a RESTful Node.js server and a client-side built with JavaScript/Zepto. I have encountered an issue when trying to send a JSON string from my client to the server. Below is the code ...

Retrieve information from two tables in mySQL and merge them together

When trying to select data from two tables in my database - comments and users, I encountered an issue. The structure of these tables is as follows: comments: commentID | commentDateAndTime | imageID | userID | comment users: userID | username My goal ...

Obtain JSON Object based on property using jq in Bash

Looking at some JSON objects that follow this structure: { "name": "thing1", "important_value": "42", "other_value": "27" } { "name": "thing2", "important_value": "13", "other_value": "5" } { "name": "thing3", "important_value": "788", "other_val ...

How can I ensure that each callback is passed a distinct UUID?

I am utilizing a package called multer-s3-transform to modify the incoming image before uploading it to my bucket. Below is the code snippet of how I am implementing this: const singleImageUploadJpg = multer({ storage: multerS3({ s3: s3, bucket: ...

Monitoring the modifications of a linked component in React: A guide

I am facing an issue where I need to store the text of a referenced element in an array. My goal is to first display the text of each paragraph element with the "ebookName" class in the console before storing it in the array. However, I have encountered a ...

Enhancing Rails functionality with drag-and-drop to modify object attributes

I work with two main models: Collections and Images Collection Model class Collection < ActiveRecord::Base has_many :images, dependent: :destroy accepts_nested_attributes_for :images end Image Model class Image < ActiveRecord::Base belongs_ ...