Transform an array of Boolean values into a string array containing only the values that are true

Suppose we have an object like the following:

likedFoods:{
  pizza:true,
  pasta:false,
  steak:true,
  salad:false
}

We want to filter out the false values and convert it into a string array as shown below:

compiledLikedFoods = ["pizza", "steak"]

Is there a more efficient way to achieve this without using multiple if statements like this:

if (this.likedFoods.pizza == true) {this.compiledLikedFoods.push('pizza')};
if (this.likedFoods.pasta == true) {this.compiledLikedFoods.push('pasta')}'
if (this.likedFoods.steak == true) {this.compiledLikedFoods.push('steak')}'
if (this.likedFoods.salad == true) {this.compiledLikedFoods.push('salad')}'

If so, what would be the best approach?

Thank you.

Answer №1

I prefer to extract object keys based on their corresponding values

const favoriteFoods = {
  pizza:true,
  pasta:false,
  steak:true,
  salad:false
};
const selectedFood = Object.keys(favoriteFoods).filter(key => favoriteFoods[key] === true);
console.log(selectedFood); //["pizza", "steak"]

Answer №2

If I were to tackle this task, I might opt for either using a loop or leveraging the reduce function on the array obtained from Object.entries:

Utilizing a Loop:

const compiledLikedFoods = [];
for (const [name, value] of Object.entries(likedFoods)) {
    if (value) {
        compiledLikedFoods.push(name);
    }
}

Implementing reduce (as any array operation can be molded into a reduce):

const compiledLikedFoods = Object.values(likedFoods).reduce((array, [name, value]) => {
    if (value) {
        array.push(name);
    }
    return array;
}, []);

However, you may want to check out Andrey's more straightforward solution. (I'm feeling a bit embarrassed now.)

Answer №3

If you want to filter by value, simply retrieve the keys and then apply the filtering logic.

var favoriteMovies = { action: true, comedy: false, drama: true, horror: false },
    compiledFavoriteMovies = Object.keys(favoriteMovies).filter(k => favoriteMovies[k]);

console.log(compiledFavoriteMovies);

Answer №4

If you need to iterate through an object and add keys to an array based on their corresponding true values, you can utilize the for...in loop:

var likedFoods={
  pizza:true,
  pasta:false,
  steak:true,
  salad:false
}
var compiledLikedFoods = [];
for(var o in likedFoods){
  if(likedFoods[o])
    compiledLikedFoods.push(o);
}
console.log(compiledLikedFoods)

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

Generating JSON data on the fly using D3.js scripting

I am attempting to create a JSON object dynamically by pulling data from an array in D3 JavaScript. (The code below is not the exact one I used, but similar) let radius = [10,20,30]; let jsonradius = '[{'; for (let i = 0; i < radius.le ...

Updating cluetip content post webpage loading

I need to update the content within a cluetip after the page has finished loading. Imagine there's a button inside the cluetip and upon clicking it, I want it to disappear. Here is the cluetip setup: $('a.notice_tooltip').cluetip({activa ...

The ng-view DIV in Angular JS 1.x mysteriously vanishes

Currently, I am working on a project that involves angularJS and ASP.NET in Visual Studio 2013. However, I have encountered a frustrating issue where my DIV node for ng-view is being replaced with an ng-view comment without any errors appearing while testi ...

Struggling to make vue-i18n function properly with nuxt generate?

In an effort to enhance my skills, I am creating a small Nuxt project from scratch. While the project runs smoothly on the local server, I have encountered an issue with the language switcher not updating the translation fields when using nuxt generate. U ...

What is the best way to transfer React context between _document.js and pages in Next.js?

Imagine I have this scenario: export const ThemeContext = createContext(); export function ThemeWrapper({ children }) { const sharedState = { darkMode: false, }; return ( <ThemeContext.Provider value={sharedState}> {children} ...

The failure to parse an object in response to a JavaScript AJAX call

Why am I getting undefined in the console? Javascript code: var url = "/SitePages/AlertsHandler.aspx/GetAlert"; $.ajax({ type: "POST", url: url, data: '{alertId: \"' + alertId + '\"}', contentType: "applicati ...

Choose dropdown choices using Node.js, MySQL, and EJS

I am looking to create a dropdown list using data from my MySQL database. Specifically, I want to populate the names from the "customer" table in the select option of my "create budgets" form using EJS. However, I am encountering issues with passing EJS da ...

The Concept of Static Block in TypeScript

For the purpose of testing Network Encoding/Decoding Logic, I have implemented a pair of test cases in both Java and JavaScript. These tests utilize Data Providers which essentially consist of various Constants. In my Java test case, I have a Data Provide ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

Setting the value for a textbox using Jquery's .val() function works, while .attr() does not have the

//unable to get it working $("#TextBoxID1").attr("value","HI Value Change") //works perfectly fine $("#TextBoxID2").val("HI Value Change") <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type= ...

Automatically substitute a term with a clickable link

Is there a way to automatically turn every word into a hyperlink? I have specific words that need to be linked. For example, I want Ronaldo (Only for the First Appearance) to link to a certain page. However, my attempted method did not work. <p> Ro ...

Is there a simple and efficient method to transition the loading of a regular website to AJAX for the entire site?

Is it feasible to easily and quickly change all links on a website to load the URL that the user clicked via AJAX, rather than refreshing the webpage? My website currently has standard links, but in order to create a mobile application for iPhone, I need ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

The instance of my ObjectType is coming back as an empty entity

Having trouble making relationships between two object types in my code. One of them is working fine, but the other one returns an empty object and I can't seem to find the issue. The first one works as expected and logs the rank type without any pro ...

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

Error in Webpack: JSX elements that are adjacent must be enclosed within a wrapper tag

After adding a new component and integrating it into my Main component, I encountered an error when running webpack. The error message displayed was: "Adjacent JSX elements must be wrapped in an enclosing tag" Below is the snippet of code where the iss ...

Having trouble with [at-loader] while incorporating Typescript and react-bootstrap in webpack?

While working with webpack, I encountered an error message when using a component in react-bootstrap along with typescript. The error displayed is as follows: ERROR in [at-loader] ./node_modules/react-bootstrap/esm/NavbarCollapse.d.ts:4:18 TS2320: ...

What is the best way to implement a subquery using EXISTS in Knex?

I'm currently facing challenges while constructing a query using knex, specifically when it comes to incorporating the 'WHERE' clause with the condition EXISTS (SELECT * FROM caregiver_patient WHERE patient_id IN (0,1)). Below is the origin ...

Effective methods for importing components in VueJS 2.0

As a newcomer to VueJs, I have a question regarding the best practice for importing components in a Vue Template Project. I currently have some components that are used in multiple views. After downloading an admin template, I noticed that the samples alwa ...

Why is inner HTML returning input/textbox instead of the value?

I need help extracting the value from an input/textbox within a table cell. Although the rest of my code is functioning correctly, I'm struggling to retrieve the value from this particular input element. I've attempted to access the value using ...