I desire to add the item into a fresh array if the cost is higher than 1

I am seeking to utilize JSON data in order to extract an object from the JSON structure where the "free" attribute has a value greater than 0. This extracted object will then be added to a new array. For instance, I aim to include {"free": 1, "used": 0, "total": 0, "usd_price": 0} in the array and generate a result like this [{"free": 1, "used": 0, "total": 0, "usd_price": 0}, {"free": 1, "used": 0, "total": 0, "usd_price": 0}]

{
"success": true,
"message": "",
"data": {

    "BIT": {
    "free": 0,
    "used": 0,
    "total": 0,
    "usd_price": 0,
    "usd_val": 0,
    "percent_change_24h": 0,
    "usd_pnl_24h": 0,
    "name": "",
    "logo": "https://www.trailingcrypto.com/assets/img/default-coin.png",
    "portfolio_share": 0
    },

    "BTC": {
    "free": 0,
    "used": 0,
    "total": 0,
    "usd_price": 38400.82298054895,
    "usd_val": 0,
    "percent_change_24h": 0,
    "usd_pnl_24h": 0,
    "name": "Bitcoin",
    "logo": "https://s2.coinmarketcap.com/static/img/coins/128x128/1.png",
    "portfolio_share": 0
    },
    "DOT": {
    "free": 0,
    "used": 0,
    "total": 0,
    "usd_price": 20.07605927484185,
    "usd_val": 0,
    "percent_change_24h": 0,
    "usd_pnl_24h": 0,
    "name": "Polkadot",
    "logo": "https://s2.coinmarketcap.com/static/img/coins/128x128/6636.png",
    "portfolio_share": 0
    }

}
}

Answer №1

To achieve the desired outcome, Javascript's filter method can be utilized to extract a sub-array that meets a specific condition - in this case, ensuring that the value of free is greater than 1. However, as the filter method is applicable only to an array, and the provided data is structured as an object.

Prior to applying the filter method, it is necessary to convert the object into an array using Object.values().

Object.values(json.data)

Once the data is transformed into an array format, the filter method can be implemented to obtain a relevant subset from the original array (specifically the elements where the value of free exceeds 1).

Object.values(json.data).filter((data) => data.free > 1)

The code should now function as intended. The complete working code snippet is displayed below:

const json = {
  success: true,
  messsage: "",
  data: {
    BIT: {
      free: 0,
      used: 0,
      total: 0,
      usd_price: 0,
      usd_val: 0,
      percent_change_24h: 0,
      usd_pnl_24h: 0,
      name: "",
      logo: "https://www.trailingcrypto.com/assets/img/default-coin.png",
      portfolio_share: 0,
    },

    BTC: {
      free: 0,
      used: 0,
      total: 0,
      usd_price: 38400.82298054895,
      usd_val: 0,
      percent_change_24h: 0,
      usd_pnl_24h: 0,
      name: "Bitcoin",
      logo: "https://s2.coinmarketcap.com/static/img/coins/128x128/1.png",
      portfolio_share: 0,
    },
    DOT: {
      free: 0,
      used: 0,
      total: 0,
      usd_price: 20.07605927484185,
      usd_val: 0,
      percent_change_24h: 0,
      usd_pnl_24h: 0,
      name: "Polkadot",
      logo: "https://s2.coinmarketcap.com/static/img/coins/128x128/6636.png",
      portfolio_share: 0,
    },
  },
};

const free = Object.values(json.data).filter((data) => data.free > 1);

console.log(free)

Answer №2

Store objects in an array and then iterate through the array to check if the 'free' property is equal to one. If true, add the object to a second array.

let filteredData = [];
const response = {
  success: true,
  messsage: "",
  data: {
    BIT: {
      free: 0,
      used: 0,
      total: 0,
      usd_price: 0,
      usd_val: 0,
      percent_change_24h: 0,
      usd_pnl_24h: 0,
      name: "",
      logo: "https://www.trailingcrypto.com/assets/img/default-coin.png",
      portfolio_share: 0,
    },
    BTC: {
      free: 0,
      used: 0,
      total: 0,
      usd_price: 38400.82298054895,
      usd_val: 0,
      percent_change_24h: 0,
      usd_pnl_24h: 0,
      name: "Bitcoin",
      logo: "https://s2.coinmarketcap.com/static/img/coins/128x128/1.png",
      portfolio_share: 0,
    },
    DOT: {
      free: 1,
      used: 0,
      total: 0,
      usd_price: 20.07605927484185,
      usd_val: 0,
      percent_change_24h: 0,
      usd_pnl_24h: 0,
      name: "Polkadot",
      logo: "https://s2.coinmarketcap.com/static/img/coins/128x128/6636.png",
      portfolio_share: 0,
    },
  },
}

Object.values(response.data).map((item) => {
   if (item?.free === 1) {
     console.log("ok");
     filteredData.push(item);
   }
});
// You now have access to the filtered data
console.log(filteredData)

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

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

Cease an if condition in AngularJS JavaScript

I am facing a situation where I have an if statement that needs to halt execution but only after certain processes have been completed. This if statement is enclosed within a forEach loop in an Angular context. angular.forEach($scope.obj, function ( val ...

unable to implement $http method in angular.js

I am attempting to retrieve data from a web API. When running on a single HTML page, I receive the response with the data successfully. However, if this script is written separately (outside the HTML page), I am unable to fetch the data. This is the first ...

When is the appropriate time to provide arguments to the constructor of a TypeScript service?

I am grappling with the concept of when to pass arguments to a service's constructor versus passing them in the execution of the service. For instance, I have a service that filters rows from an Excel sheet: @Injectable() export class FilterRowsServi ...

Using RegEXP in Javascript, you can easily eliminate characters that fall between two special characters without removing the special characters

I'm facing an issue with a string that looks like this: var str = "1111 type reallycoolsentence\text.json\n1111 type anotherreallycoolsentence text2.json My goal is to eliminate the characters located between the backslashes in the str ...

The functionality of Flatbutton(Input handler) appears to be malfunctioning

I am having trouble with the file uploader from Material-UI. It doesn't seem to be working properly when I try to select a file. Does anyone have any suggestions on how to handle the input from the file selector? <FlatButton icon={< ...

Troubles with Vue and localStorage for storing a theme's data

I've been struggling with this issue for a while now while working on a Vue site. I have not been able to find a solution for my specific bug in other discussions. The concept should be straightforward - I want to have a switch that toggles a value b ...

Using jQuery to eliminate selected item from a list

I have a basic list in html/jquery that allows users to add items. I am trying to create functionality where a specific item can be removed from the list when clicked on. However, the code for removing the item is not working as expected. Remove Item Code ...

Error encountered when attempting to use setInterval: '$' not located

I'm attempting to programmatically click a button as soon as it's created, and then close the interval. However, I'm encountering an error that says $ is not defined when running the script below. Can someone assist me in identifying where m ...

Creating accurate JSON data using p-dropdown PrimeNG

I recently started learning Angular and encountered a situation while using the Java API: In my Release class, the category is not required (class Category). @Entity @Table(name = "release") public class Release { @Id @GeneratedValue(strategy = G ...

What is the process for utilizing a .js file as a node command on a global scale?

I have a .TS file that contains all of my utility functions for various projects. Every time I need to use these functions, I find myself copying and pasting the file into the project folder. I am familiar with node scripts and FS for file system manipulat ...

system for responding to comments by identifying unique id values

Hey folks! I've got a blog post page with a comment and reply system that's mostly working great. The only issue is that when I try to add a reply to a comment, it always ends up replying to the first comment instead of the one I clicked on. I su ...

Is there a way to transform standard JSON data into a format that can be interpreted by Google Visualization

Recently, I delved into the world of Google charts and was amazed by its capabilities. However, I encountered a hurdle when trying to integrate data from a SQL server view. To tackle this issue, I initiated a sample project to facilitate the process but ha ...

SBJSON encountered an issue when processing JSON data containing binary information

Currently, I am utilizing a web service and sbjson for parsing the data that is received. The code snippet used for this purpose looks like: NSDictionary *response = [[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]JSONValue]; This metho ...

What is causing the error message "TypeError: string indices must be integers" to appear in my code?

Upon reviewing the JSON file provided below, I encountered an error Traceback (most recent call last): File "test11.py", line 10, in <module> print(driver['id']) TypeError: string indices must be integers {"drivers": [ ...

Launch a fresh fancybox once the previous one has exited

I am currently facing an issue with my password change process through a fancybox window. Whenever a user enters the wrong password, a "Wrong Password" iframe opens up. However, the challenge arises when I try to reopen the "Password Change" iframe after c ...

Concealing alert messages automatically in CodeIgniter PHP after a certain amount of time

After attempting to use a script to hide the flash message once displayed, I found that it was not working as expected. The flash message remains visible until the page is refreshed. Controller: if ($this->email->send()) { $this- ...

Using JavaScript to sort through JSON data arrays

I am dealing with a JSON data structure as shown below: var data = [ { "type": "Feature", "id": 1, "properties": { "name": "William", "categorie": 107, "laporan":"Fire", "time":1, ...

The custom binding fails to trigger the update

Currently, I am dealing with a system that utilizes a combination of Knockout.js and Jquery Mobile UI. One issue that arose was applying Jquery Mobile to elements with knockout :if bindings. Initially, we tried triggering events in the page cycle when ko.a ...

Applying the SELECTED attribute to a jQuery HTML dropdown menu filled with options from a PHP array

I am currently iterating through an array of items and displaying these options using JQuery in an HTML SELECT element. My goal is to compare the current item in the array with a previously selected variable and then set the <option> attribute to se ...