The object returns true when the specified condition matches the key within the object

I need assistance with a specific object query. I am looking to execute the filter function in order to retrieve a list of keys from an object where the condition is true, as shown below:

myObject = {
   key1: {
     name:"key1",
     select:true
   },
   key2: {
     name:"key2",
     select:false
   },
   key3: {
     name:"key3",
     select:true
   }
}

Due to certain requirements, I must now add a specific key and want to return an array containing only the keys with the value true.

arrayWantreturn = ["key1", "key3"]

Your assistance with this would be greatly appreciated.

Answer №1

To create a loop using the given object, follow this code:

var myObject = {
   key1: {
     name:"key1",
     select:true
   },
   key2: {
     name:"key2",
     select:false
   },
   key3: {
     name:"key3",
     select:true
   }
};

var arr = [];

for (var prop in myObject) {
    if (myObject[prop].select) {
        arr.push(myObject[prop].name);
    }
}

console.log(arr);

Answer №2

If you're looking for a solution, you might want to give this code snippet a try:

const myObject = {
   key1: {
     name:"key1",
     select:true
   },
   key2: {
     name:"key2",
     select:false
   },
   key3: {
     name:"key3",
     select:true
   }
};

const result = Object.entries(myObject)
                     .filter(([k, v]) => v['select'])
                     .flatMap(e => e[1].name);

console.log(result);

Hopefully, this provides some clarity!

Answer №3

To access the values of your object, utilize the Object.values() method. Filter out all objects with a `select` property set to `true` using the .filter() function. Then, use the .map() method to extract the `name` property from each remaining object.

const myObject = { key1: { name:"key1", select:true }, key2: { name:"key2", select:false }, key3: { name:"key3", select:true } };
const res = Object.values(myObject)
              .filter(({select}) => select)
              .map(({name}) => name); 
      
console.log(res);

This technique involves utilizing destructuring assignment to access the inner properties within the callback functions.

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

"Troubleshooting: Why is my jQuery .load function returning an empty div when

Currently, I am developing a PHP control panel and I need a div in one of my PHP files to automatically refresh. After researching, I found a jQuery solution that can reload specific parts of a website automatically. However, the issue I am facing is that ...

Encountering issues with gulp-angular-templatecache while processing angular templates through pipelining

I've encountered an issue with gulp-angular-templatecache in my gulpfile. Here's the task causing trouble: gulp.task('templates', function() { return gulp.src(paths.angularTemplates) .pipe(templateCache()) ...

What is the name attribute of an ES2015 function?

var individual = { announceIdentity() { console.log(this.identity); }, get firstID() { return "Superman"; } }; individual.announceIdentity.identification // "identity" individual.firstID.identifier // "get firstID" I recently came acros ...

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Leveraging AJAX for connectivity to the Twitter API

Considering incorporating Twitter functionality into my web application, I decided to conduct some tests. After researching how to call the search Twitter URL (more information available at: ) in order to retrieve tweets containing specific words or phrase ...

What are the steps to showcase a randomly generated number in a live Flot chart using Json?

In my C# page, I have created a random number stored in a json object: if (method == "rnd") { //Random number this.Page.Response.ContentType = "application/json2"; Random rnd = new Random(); int nr = rnd.Next(1, 100); // generates a number ...

The Meteor Call object stands apart from the Meteor Method object that was received

When I send an object from the client to the server using a Meteor Call and Meteor method, something strange happens. The object is received in the Method but it looks different - nested within the giftList. Meteor Call - JSON.stringify {"personName& ...

capture the alteration of text within an input field

Currently, I am utilizing the Joomla calendar feature to select a date. The HTML code for this functionality is displayed below. When you click on the image, a calendar will pop up allowing you to choose a date. Once selected, the popup closes and the date ...

What is the best way to streamline a state-dependent getter, with a focus on adhering to SOLID principles?

Is there a more user-friendly way to retrieve different data based on the type in my Angular component? I'm considering separating the component into two: one for phone and one for email. However, I'm concerned about duplicating most of the logi ...

Disregarding TypeScript import errors within a monorepo ecosystem

In my Turborepo monorepo, I have a Next.js app package that imports various components from a shared package. This shared package is not compiled; it simply contains components imported directly by apps in the monorepo. The issue arises with the shared co ...

Remove an element from an array using a different array

Well, I'm at a loss for words on how to describe this. Let's say I have this session array: $_SESSION['users']['currentuser']['username'] = 'stijn'; This array is constructed dynamically. Therefore, I al ...

Preventing Past Dates from Being Selected in JQuery Date Picker

Need help with a date picker that only allows selection of the 1st and 15th dates of each month. How can I prevent users from selecting previous dates? <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" ty ...

Ionic JavaScript function runs independently of promise resolution

Within my ngOnInit on a page, I have a method that is meant to fetch data. However, it seems like the other methods in the chain are executing before the fetch data process is complete. Here's a snippet of the code: ngOnInit() { this.devicesinfo.fetc ...

Utilize React-Charts.js-2 with ChartJS to create a customized bar chart

When creating bar graphs based on monthly data, everything works fine expect for the fact that the order of the months is not maintained and it appears mixed up in each rendering. The API provides the following data: { { "_id": 2022, &qu ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

Using javascript, retrieve the JSON values for each level

I need help using a recursive function in JavaScript to retrieve the last key value pair from a simple JSON object. Here is an example JSON object: { 'a': { 'b': { 'c': 12, 'd': 'Hello World& ...

Integrating tooltips on Dimple.js line charts

A simplified network-style chart has been created using Dimple's line plot as the foundation. For example, please refer to this link: http://jsfiddle.net/cc1gpt2o/ myChart.addCategoryAxis("x", "Entity"); myChart.addCategoryAxis("y", "Entity").add ...

Retrieve the text input from the text field and display it as

Is there a way to display what users enter in a textfield when their accounts are not "Activated"? Here's an example: if(active == NULL);{ //I've attempted the following methods. //In this scenario, 'username' is the name of ...

Switch the contenteditable HTML attribute in a dynamically generated table using PHP

Despite finding numerous articles and solutions, my code still refuses to work. What could I be overlooking? Below is a snippet of the code where the crucial part is marked at the comment '! HERE') <!-- Table with grades --> <table clas ...

Ways to access the scrollTop attribute during active user scrolling

I've been working on a website that utilizes AJAX to keep a chat section updated in real-time. One issue I encountered was ensuring the chat automatically scrolled to the bottom when a user sent a message, but remained scrollable while new messages we ...