Loop through the keys of an object to retrieve only the valid values

Task Description: Develop a function named displayOptions that takes an object called "displayDevice" as input and returns an array. The properties of the input object will be various "video output" options, each with either a true or false value. Your task is to extract all the names of the "video output" with true values.

I attempted to solve this problem using the .filter() method, but I would like to explore a solution utilizing a for..in loop. While I managed to iterate through the object, my current implementation includes all keys in the array, not just the ones with a "true" value. Please help me identify where I went off track in my approach.

Here's My Current Code:

function displayOptions(displayDevice) {
  for(var key in displayDevice) {
    if(displayDevice[key] === true) {
      return Object.keys(displayDevice);
    }
  }
}

var televisionA = {
  VGA: false,
  HDMI1: true,
  HDMI2: true
}
var monitor001 = {
  VGA: true,
  DVI: false,
  HDMI1: true,
  HDMI2: true
}
var monitor002 = {
  HDMI1: true,
  HDMI2: true,
  DVI: true
}

displayOptions(televisionA); //["HDMI1", "HDMI2"];
displayOptions(monitor001); //["VGA", "HDMI1", "HDMI2"];

Answer №1

The issue at hand is that the code currently returns all keys of an object when it encounters the first key with a value of `true`, instead of only pushing keys with a value of `true` to a new array. To address this, it would be more effective to create a new array and append keys with a value of `true`. You can refer to Object.keys() for further clarification on its usage.

function generateKeys(object)
{
    let newArray = [];

    for (var key in object)
    {
        if (object[key] === true) 
            newArray.push(key);
    }

    return newArray;
}

var newObj1 = {
  item1: false,
  item2: true,
  item3: true
}
var newObj2 = {
  item1: true,
  item2: false,
  item3: true,
  item4: true
}
var newObj3 = {
  item1: true,
  item2: true,
  item3: true
}

console.log(generateKeys(newObj1)); // ["item2", "item3"];
console.log(generateKeys(newObj2));  // ["item1", "item3", "item4"];

Answer №2

Discover how to retrieve keys using Object.keys and efficiently filter them based on true or false values

var televisionA = {
  VGA: false,
  HDMI1: true,
  HDMI2: true
}
var monitor001 = {
  VGA: true,
  DVI: false,
  HDMI1: true,
  HDMI2: true
}
var monitor002 = {
  HDMI1: true,
  HDMI2: true,
  DVI: true
}
console.log(Object.keys(televisionA).filter((e)=>televisionA[e]))
console.log(Object.keys(monitor001).filter((e)=>monitor001[e]))
console.log(Object.keys(monitor002).filter((e)=>monitor002[e]))

Answer №3

Streamlining the filtering process:

function listFeatures(device) {
  return Object.entries(device).filter(([, status]) => status).map(entry => entry[0]);
}

var laptop1 = {
  WiFi: true,
  Bluetooth: true,
  HDMI: false
}
var tablet1 = {
  WiFi: true,
  Bluetooth: false,
  USB: true
}
var phone1 = {
  WiFi: true,
  GPS: true,
  NFC: true
}

console.log(listFeatures(laptop1));
console.log(listFeatures(tablet1));

Answer №4

Looking ahead, in case it hasn't been mentioned yet, an additional option to consider is using the reduce method:

const filterOptions = filterCriteria =>
  Object.entries(filterCriteria)
    .reduce((accumulator, [property, value]) => (value && accumulator.push(property), accumulator),[]);

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

The mssql node is experiencing an issue where it is unable to accept work due to the pool being

Recently, I encountered an issue with my node js app that utilizes the npm mssql module. Despite purchasing a cloud Windows 2012 server, I faced an error when trying to execute a stored procedure. The error is thrown at ps.prepare("exec usp_Get_Cars @para ...

Arrays in the C programming language are organized into rows and columns using

I'm struggling with the syntax, but I need to create a 2D array with the first element containing pointers to CSTRINGs and the second element being a counter. This is for threading purposes, specifically for passing word lists to threads based on the ...

Display routes in React using the react-router package

Can I use a console command at runtime to display all routes in my application? Despite utilizing react-router, not all routes seem to be functioning properly. In Rails, you can retrieve a list of routes during runtime. ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

Finding the variable with the highest value using AngularJS

I have a variety of variables with different values assigned to them, such as: Weight_gain = 0.01 Weather_gain = 0.02 and many more like these. My goal is to determine the variable name with the highest assigned value. When I attempt this using code, it ...

Getting pictures dynamically from the backend with unspecified file types

Greetings to my fellow Stackoverflow-Users, Lately, I was tasked with the requirement of loading images dynamically from the backend into my application. Up until now, it was always assumed that we would only be dealing with SVG images since there was no ...

Closing Modals in ReactJS Hooks with Parent and Child Components

I have a scenario where I am successfully opening a Model (child Component) on Button Click from the Parent Component. However, the issue arises when trying to close the modal as it displays an error message: Uncaught TypeError: setOpen is not a functio ...

Monitoring Clicks within an Iframe

Is there a way to track a click event on a hyperlink within an iframe using Google Analytics? The iframe is located within the same domain as the main page. How can this be achieved? The iframe is added dynamically to the page after it has loaded. Is i ...

Is there a way to extract JSON keys that begin with a numerical value?

I am attempting to retrieve JSON data from sparkfun using ajax: var token = "someToken"; var jsonData = $.ajax({ url: "https://data.sparkfun.com/output/" + token + ".json", data: { page: 1 }, dataType: "jsonp", }).done(function (results) { ...

AngularJS ng-repeat doesn't refresh following an Ajax request

I am using an AngularJS application where I have a chat feature on the right side for communication with my clients. Here is the HTML code: <div class="recent" ng-show="show_chat_list"> <h2></h2> <div ng-repeat="customer in r ...

The design problem arises from using jQuery to dynamically prepare the table body at runtime

The table row and data are not appearing in the correct format. Here is a link to the problem on Fiddle: http://jsfiddle.net/otc056L9/ Below is the HTML code: <table border="1" style="width: 100%" class="eventtable"> <thead style="color: b ...

Using AngularJS to fetch Google OAuth2 tokens

Every time I initiate this call, it triggers the account selector to open. Following which I can choose one of my Google accounts, but upon selection, an error occurs. Error: invalid_request Missing required parameter: scope The URL in the account selec ...

A guide on utilizing Java's Collections to organize a list filled with objects from a class

Struggling to figure out how to properly sort this list. When I attempt to use Collections.sort(mylist);, an error surfaces that is beyond my comprehension due to my beginner status in Java. Myclass x1 = new Myclass("8", "12"); Myclass x2 = new Myclass("6 ...

Scheduled Job unable to complete post request

(I am completely new to the world of JavaScript, node.js, and Heroku so I apologize in advance if my question is not very clear) I recently set up a Heroku node.js application with a scheduled task that should run every hour. The task does run as expecte ...

Converting human-readable dates into a Date object

How can I reliably convert human-entered dates into a Date() object for my project that utilizes a ML text extractor? Although seemingly straightforward, the issue lies in the wide variety of formats used by individuals when entering dates, ranging from " ...

How can we ensure that the user's language preference is saved?

I'm currently working on implementing a language switcher feature for a website I've been developing. I'm facing an issue where the site doesn't remember the user's language preference and keeps reverting back to English. Any ass ...

Issue with Mat-AutoComplete arising while utilizing a formArray

After adding a form array to account for multiple rows, I had to modify my definition from: shoppingCartList Observable<any[]>; to shoppingCartList: Observable<any[]>[] = [];. However, this change resulted in an error in my filter function whic ...

Angular allows you to set specific conditions for when a failed HTTP request should be retried, and you can also specify the number of attempts that should be

Within my angular application, I have a post request that needs to be retried based on the error message, but with a limit on the number of attempts. Initially, I attempted the following approach: public post(url, data) { this._http.post(url, data).pi ...

I have implemented the Angular "Date" filter, but I'm unsure about the meaning of this numerical value

The Angular tutorial showcases the date filter with the following example: {{ 1304375948024 | date }} --> May 2, 2011` How would you notate the expression 1304375948024? ...

Suggestions on coloring polyline segments according to the density of neighboring segments surrounding the specific polyline segment

Apologies for the lengthy title, but I am interested in developing a polyline heatmap that changes color based on the number of lines within a certain proximity. Here is an example of what I have in mind: https://i.sstatic.net/W2lox.jpg Are there any inn ...