What is the method for extracting dynamic JSON keys with a value of true?

Here is the JSON response I received:

{
  "A":{"Option1":true,"Option2":true,"Option3":false}
  "B":{"OptionX":true,"OptionY":true,"OptionZ":false}
 }

I am attempting to extract the following values into a string: Option1, Option2, OptionX, OptionY

Despite my attempts, I have not been successful. Here is what I have tried:

  Array.from(this.model).forEach(child => {
    console.log(child, 'child name')
  });

Answer №1

Implement flatMap() alongside filter(), where you iterate through each key by utilizing the map function in conjunction with Object.keys()

const data = {
  "A": {"Option1":true,"Option2":true,"Option3":false},
  "B": {"OptionX":true,"OptionY":true,"OptionZ":false}
};
 
const res = Object.values(data).flatMap(o => Object.keys(o).filter(k => o[k]));

console.log(res)

Answer №2

Iterating through the JSON object to retrieve keys with non-null values using two different methods in JavaScript: 

Method 1:
for (const record of Object.values(json)) {
  for (const [key, value] of Object.entries(record)) {
    if (value) {
      console.log(key);
    }
  }
}

Method 2:
const keys = Object
  .values(json)
  .map(record => Object
    .entries(record)
    .filter(([key, value]) => value)
    .map(([key]) => key)
  )

Answer №3

def filter_options(obj):
    result = []
    for key, value in obj.items():
        if value:
            result.append(key)
    return result

obj = {
  "A": {
    "Option1": True,
    "Option2": True,
    "Option3": False
  },
  "B": {
    "OptionX": True,
    "OptionY": True,
    "OptionZ": False
  }
}

result = filter_options(obj)

print(result)

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

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Implementing a dynamic table filter for every column using AngularJS

I have been working on a project to create a custom directive that generates a table with dynamic data and allows for sorting of columns. While the sorting function works as intended, I now want to implement filtering on all columns without specifying a sp ...

Attempting to retrieve user information from Blockstack on a web browser

Currently developing a web application integrating Blockstack and encountering challenges with Javascript implementation and understanding how to effectively use Blockstack in the browser. My issue arises when retrieving the Blockstack user's ID or u ...

A method for assigning a single event listener to multiple events in a React component

I find myself in a situation where I have two events, onClick and onSelect, both of which share the same event handler. I am wondering what the most efficient way to handle this scenario would be - should I create a common method and then call the event ...

Animating an object in Three.js as it transitions smoothly between two different positions

If I have an object positioned at position.x = 0 and I wish to animate it smoothly to position.x = 2.435 in the render loop, how can I achieve this effect? ...

View two tiled images side by side and seamlessly load them in real-time with our innovative image viewer

Currently, I am working on creating a webpage where two tiled images can be loaded and displayed side by side. The goal is for these images to zoom in together but remain separately tiled. After doing some research, it seems that using Seadragon may not al ...

Is there a way to listen for the validation of an HTML5 form before it is submitted?

I've been trying to figure out a way to detect if a form has been validated, but so far, no luck. For example: User clicks the submit button The form is invalid, so the submit event doesn't occur At this point, I want to add the class .form-fe ...

Why does jQuery only execute the very first condition or none at all if the first condition is false?

I'm trying to create a fixed button that, when clicked, scrolls to a specific section on the page. However, only the first condition seems to be working, and the other conditions are being ignored even when the first one is false. Can you help me figu ...

Exploring AJAX GET requests and JavaScript capabilities

Just starting out with javascript and I'm a bit confused about how to solve a particular issue. Hopefully, the example below can help explain my situation: let tasks = { '04-23-2018' : '<a href="http://tympanus.net/codrops/201 ...

What is the best way to create a fixed sidebar or top bar that remains visible as I move to different pages?

Whenever I navigate to other pages, the sidebar mysteriously disappears. As I work on my project about an admin page, I'm wondering if it's necessary to include every single page? ...

Looking to reallocate information, paginate, and sort each time a new row is added to the mat-table

In my application, I have a customized <mat-table> with an implemented addRow() function that adds a new row to the table using default values based on the data type. The challenge I'm facing is that each time a new row is added, I find myself ...

Is there a way to prevent Javascript from recognizing the escape ( ) character?

qAnswersR[12456] = []; qAnswersR[12456].push("[math]m: \frac{(x+20)^{2}}{256}+\frac{(y-15)^{2}}{81}=1[/math]"); To store the value in a variable, I tried logging the array like this: console.log(qAnswersR[12456]); The result displayed was ...

Group objects with the same id in an array into separate arrays

Suppose I have an array of objects called 'myArray' that is populated as follows: var myArray = []; The objects in 'myArray' are structured like this: var myObject = { id: 1, name: 'example' }; If 'myArray' co ...

Determining the return value using Typescript inference with multiple subclasses of Error

My function is designed to return either a number, an Error, or a NegativeError: class NegativeError extends Error { name = 'NegativeError' } function doThing (a: number): number | NegativeError | Error { return a < 0 ? new NegativeError( ...

Issue with Highcharts: The useHTML flag is not functioning properly when trying to render labels

Currently, I am utilizing highcharts and a phantomjs server for rendering charts and labels. However, I have encountered an issue where the useHTML flag does not function as expected when rendering the labels. Following the instructions in the documentatio ...

Efficiently assign multiple attributes using a single d3 function

Hey everyone! I'm currently working with SVG lines and have come across an example object that looks like this: { _id: 5, coordinates:{ x1: 100, y1: 100, x2: 500, y2: 500, } Now, imagine I have an array of these obje ...

Retrieve Textures From an Assortment

Greetings to all the readers here! I am in the process of developing a website where I want to implement a feature that allows me to scroll through "cards" arranged in a single line, visible from an isometric side view. I have managed to set up the scene ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Waiting for the completion of the ScrollIntoView operation using Selenium

Whenever I try to scroll to a specific element and take a screenshot of the page, the driver captures the screenshot before the page has fully scrolled to the element. To address this, I initially included a time sleep in my code: driver.execute_script(&qu ...

If one check box is selected, the other check box will automatically vanish

In my code snippet below, I have set up a section that functions as intended. However, I am encountering an issue where the shopping cart box remains even after deselecting the first checkbox. My goal is to have the top box act as the main controller, so i ...