Filtering JSON array is just as simple as working with XML

During my project, I have transitioned from using XML format to JSON format. The XML structure includes nodes such as:

<Creature>
    <Name>Someone</Name>
    <Desert>false</Desert>
    <Woods>false</Woods>
    <Mountains>false</Mountains>
    <Swamp>false</Swamp>
</Creature>

Accompanied by a radio button list with values matching the tag names. For example:

<input type="radio" name="creature_terrain" value="Desert" />Desert<br>

In the old code, filtering the XML list was achieved through the following method:

let selector = 'Creature > ' + selectedTerrain + ':contains("true")';
var filteredCreatures = $(creaturesArray).find(selector).parent();

Now that I am working with a JSON array like:

  {
    "Name": "Someone",
    "Desert": false,
    "Woods": false,
    "Mountains": false,
    "Swamp": false
  }

I am struggling to find an elegant way to filter it compared to how it was done with XML. The only solution I can think of is utilizing switch/case statements. Any other suggestions?

Answer №1

If you're dealing with an array, utilizing the filter method can help narrow down your search for the specified terrain that is true.

UPDATE: While omitting == true would automatically evaluate as boolean, personally I find it clearer and easier to include it for readability purposes.

const creatures = [
  {
    "Name": "None",
    "Desert": false,
    "Woods": false,
    "Mountains": false,
    "Swamp": false
  },
  {
    "Name": "Swamp",
    "Desert": false,
    "Woods": false,
    "Mountains": false,
    "Swamp": true
  }
]

const terrain = "Swamp";

const creature = creatures.filter((e) => e[terrain] == true)

console.log(creature)

Answer №2

In case you have a collection of objects rather than just one object, you can utilize the filter method to refine out those objects that fulfill a specific condition.

Let's elaborate on your scenario.

  1. We have two objects (with lowercase key names). One matches "desert" and the other matches "swamp". There are corresponding radio inputs provided for illustration purposes.

  2. An event listener has been added to the fieldset element to capture events from its child elements (event delegation).

  3. Upon triggering a change event, the handler initially verifies if the element responsible for the event is a radio button. It then filters out the objects into a new array based on the condition of "is the value of this object key true?" The value of the altered radio button is utilized as the object key under examination.

  4. To enhance user experience, the refined array of objects is showcased in an output element.

const data=[{name:"Someone",desert:false,woods:false,mountains:false,swamp:true},{name:"Someone 2",desert:true,woods:false,mountains:false,swamp:false}];

// Accessing terrain and output elements
const terrain = document.querySelector('.terrain');
const output = document.querySelector('.output');

// Adding a listener to the terrain (fieldset) element
terrain.addEventListener('change', handleInput);

// Upon event capturing by the terrain element
function handleInput(e) {

  // Checking if it relates to a matching
  // creature_terrain radio button
  if (e.target.matches('[name="creature_terrain"]')) {
    
    // Setting the changed radio input's value as `key`
    const key = e.target.value;

    // Using this key in filtering conditions to identify matches
    const filtered = data.filter(obj => obj[key]);

    // Displaying the filtered objects in the output element
    if (filtered.length) {
      output.textContent = JSON.stringify(filtered, null, 2);
    } else {
      output.textContent = '';
    }
  }
}
code { display: block; margin-top: 1rem; }
<fieldset class="terrain">
  <legend>Terrain</legend>
  <input type="radio" name="creature_terrain" value="desert" />Desert
  <input type="radio" name="creature_terrain" value="swamp" />Swamp
</fieldset>
<pre><code class="output"></code></pre>

Answer №3

Utilize JavaScript's built-in array functions such as find or filter.

const filteredCreatures = creaturesArray.filter(creature => creature.Desert);

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 on maintaining the numerical value while using JSON.stringify()

Having trouble using the JSON.stringify() method to convert some values into JSON format. The variable amount is a string and I want the final value in JSON format to be a number, but it's not working as expected. Even after applying JSON.stringify(), ...

Having trouble establishing a connection from regular JavaScript to a socket.io backend? Face the issue of connection closure before

As I attempt to link my client-side JavaScript with a backend websocket service utilizing socket.io, I encounter an issue. I am attempting to establish a connection to the socket.io server using the native WebSocket object: new WebSocket("wss://localhost ...

Difficulties encountered when adjusting the size or reducing the images in a Cycle2 slideshow

Greetings to all fellow coders! Thank you for taking the time to read this post. I am currently facing a challenge in my web development project where I am trying to make my Cycle 2 slideshow images resize and reposition alongside other divs when the wind ...

Example: Utilizing data transfer from model to directive

I have a question regarding a specific part in an example from Thinkster. I believe my confusion is due to my limited understanding of JavaScript and AngularJS fundamentals. I've been teaching myself since December, starting with the basics of JavaScr ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

Retrieving data from a collection with the find() method in a custom date format

Schema for Customer Data Customers.js import mongoose from 'mongoose'; const Customers = mongoose.Schema({ CustomerID: { type: String, default: "" }, Name: { type: String, default: "" }, Email: { type: String, default: "" }, Pho ...

How can contextual binding be implemented in TypeScript?

In Laravel, you have the option to specify which class should be imported if a particular class is accessed. For example, if someone tries to use the Filesystem contract, it will return the Storage Facade (Laravel Contextual Binding). Similarly, if someo ...

Add a click function to an element in a grid when it is databound

In my TypeCtrl ES6 class angular controller, I am using a kendo datagrid directive with a template for grid config options. Within the grid template, I need to call a method from the TypeCtrl class when a span within the row is clicked. However, the functi ...

Tips for Adding or Deleting 2 Rows in a Table

When the basket icon on the right is clicked, I want to remove both the current <tr> and the yellow one as well. Check out this screenshot: This is the HTML code for the two rows that need to be deleted with a click: <tr> <t ...

Creating a menu with items and listeners from a kmllayer - a step-by-step guide

Currently, I am working with a map that includes a kmllayer. This layer has been added using the following code: ctaLayer = new google.maps.KmlLayer('http://www.npd.no/engelsk/cwi/pbl/en/aFactGlobe/disc/ActivityStatus_Producing_labels.kml'); ...

What precautions should I take when setting up my login routes to ensure security?

I am working on developing a login and registration system for a website project, but I'm unsure about the best way to safely implement the routes/logic for it. Currently, in my client-side code, I make fetch requests to either the login or register r ...

Retrieve the data-src attribute from the lightGallery plugin

I have integrated the lightgallery plugin into my website from Currently, I am struggling to retrieve the data-src value when an image is clicked. The basic HTML structure is as shown below: <div id="work-grid" class="grid wow fadeIn animated"> ...

Tips on incorporating a changing variable into a JavaScript Shader

I have successfully created a primitive sphere using THREE.SphereGeometry and applied a displacement shader to give it a bumpy effect. My goal now is to animate the scale of the bumps based on input volume from the microphone. Despite my efforts, I am stru ...

The most efficient way to invoke a jws void method in the fewest steps possible

When calling a void method of a SOAP JWS web-service using JavaScript without expecting a result back, what is the most efficient and concise approach? ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

Transferring specific form data through a POST request

I am attempting to transfer specific values from a form to PayPal once the form is submitted. Below is the code for my form: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="form-horizo ...

Is there a method available to retrieve the data values stored within these objects?

Looking at the image below, I have data that includes a Data array in JSON format. https://i.sstatic.net/WHdUw.png The Data array contains key values such as condition_type and other related values. In order to extract individual values, I am using the ...

A guide to update values in mongodb using node.js

I'm working on tracking the number of visitors to a website. To do this, I've set up a collection in my database using Mongoose with a default count value of 0. const mongoose = require('mongoose'); const Schema = mongoose. ...

What is the best way to trigger the selection options in a dropdown menu with several buttons?

Is it possible to display the options from a select-option tag using a different button? I have either a div or another button. I want to be able to show the list of options from my select tag by clicking this button. Here is my select tag: <select&g ...

Searching for attributes in a JSON document

Currently, I am dealing with a results API that provides me with a JSON file. My goal is to search for a specific property within this file. To achieve this, I first push the JSON data into an empty array and then iterate over it to retrieve the first obje ...