Sorting through boolean values within an array of objects

Here is an example of an array:

 const appoint =[
  { a: "asas",
    b:{au: false, h:false,l:true}
  },
  { a: "avd",
    b:{au: true, h:false,l:true}
  },
  { a: "as", b:{au: true, h:false,l:false}
  }];

My goal is to filter out falsy values when accessing property b. I attempted to achieve this using multiple map() functions like this:

const result = appoint.map(elem => elem.b.)
const finalresult = result.map(
         item =>item.filter(
              (item, value)=> item[value] === false )
          )

Answer №1

To start, you can utilize the map function to create a new array that only contains values from the b key. Next, use the reduce method and within the callback function of reduce, employ for..in loop to iterate through the object and extract keys that are true.

const appoint = [{
    a: "asas",
    b: {
      au: false,
      h: false,
      l: true
    }
  },
  {
    a: "avd",
    b: {
      au: true,
      h: false,
      l: true
    }
  },
  {
    a: "as",
    b: {
      au: true,
      h: false,
      l: false
    }
  }
];

let filtered = appoint.map(function(item) {
  return item.b;
}).reduce(function(acc, curr) {
  for (let keys in curr) {
    if (curr[keys]) {
      acc.push(keys);
    }
  }

  return acc;
}, []);
console.log(filtered)

Answer №2

The 'elem.b' property is an object, not an array, which means that you cannot use the filter method on it directly. One way to work around this limitation is by doing the following:

const bArray = appoint.map(elem => elem.b)
const finalResult = bArray.map(b => {
  const bKeys = Object.keys(b)
  const filtered = {}
  bKeys.forEach(key => {
    if (!b[key]) filtered[key] = false
  })
  return filtered
})

Answer №3

A custom function called getKeysBy() can be created to take an object and a predicate as input, then return the keys that meet the criteria set by the predicate.

One way to retrieve all these keys is by utilizing the Array.flatMap() method in conjunction with the getKeysBy() function.

const appoint = [{"a":"asas","b":{"au":false,"h":false,"l":true}},{"a":"avd","b":{"au":true,"h":false,"l":true}},{"a":"as","b":{"au":true,"h":false,"l":false}}]
  
const getKeysBy = (predicate, obj) => 
  Object.entries(obj)
  .filter(([, v]) => predicate(v))
  .map(([k]) => k)
  
const result = appoint.flatMap(o => getKeysBy(v => v !== false, o.b))

console.log(result)

Answer №4

If you're looking to achieve something similar, consider the following approach:

let data = [{
    item: "apple",
    details: {
        fresh: false,
        organic: true,
        sweet: true
    }
}, {
    item: "banana",
    details: {
        fresh: true,
        organic: false,
        sweet: true
    }
}, {
    item: "orange",
    details: {
        fresh: true,
        organic: false,
        sweet: false
    }
}, {
    item: "grapes",
    details: {
        fresh: false,
        organic: true,
        sweet: true
    }
}]

let result = data.filter((entry) => {
    let keys = Object.keys(entry.details)
    entry.details = keys.filter((key) => {
        if (entry.details[key]) {
            return key
        }
    })
    if (!Object.keys(entry.details).length) {
        entry.details = []
    }
    return entry;
})
console.log(result)   

The output will be:

[
    {
        "item": "apple",
        "details": [
            "organic",
            "sweet"
        ]
    },
    {
        "item": "banana",
        "details": [
            "fresh",
            "sweet"
        ]
    },
    {
        "item": "orange",
        "details": [
            "fresh"
        ]
    },
    {
        "item": "grapes",
        "details": [
            "organic",
            "sweet"
        ]
    }
]

In case none of the values are true, an empty array will be returned for that specific entry.

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

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Traveling down a linear array

I stumbled upon this intriguing question during a recent online coding challenge, but I'm struggling to make any progress. The scenario involves a 1D array composed of 0s and 1s. A player commences at index 0 and must surpass the length of the array ...

Issue with generating PDF in AngularJS: pdfMakeTypeError occurs due to inability to read 'ownerDocument' property within html2canvas

Whenever I try to export by clicking the export button, this code is triggered: $scope.export = function() { html2canvas(document.getElementById('balanceSheet')).then(function(canvas) { document.body.appendChild(canvas); ...

The State Hook error "state variable is not defined" arises due to an issue with the state declaration in

function Header() { const [keys, setKeys] = useState([]); //custom addition const first = (e) => { var result = new Map() axios.post('http://localhost:8000/' + query) .then(function(response){ var content ...

What is the best way to implement the Active list element feature in my menu bar?

The current list element is : <li class="nav__item"><a class="nav__link nav__link--active " href="#"... The standard list element is: <li class="nav__item"><a class="nav__link " href=&quo ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

Utilizing jQuery for various dynamically generated HTML elements

I am currently working on a form for editing data in my database. The form consists of three dropdowns: Category, Subcategory, and Item. These dropdowns are dynamically populated based on the selection made in the previous dropdown. After all three dropdow ...

Is there a way to transmit the ENTER key press to the page setup dialog within Internet Explorer 7?

My code is designed to change the page orientation. It functions correctly in IE6, but encounters issues in IE7. Specifically, it stops at %a and fails to input the enter or tab keys needed to press 'OK'. var shell; function SetPrintProperties() ...

NPM repository that is not accessible online

I have been looking into creating my own private NPM mirror/repository, but I'm not sure where to start. My objective is to create a repository within my private network that contains all the latest free NPM packages available on the NPM website. I w ...

Using AngularJS to implement validation on radio buttons

My application is a cross-platform app that utilizes AngularJS, Monaca, and Onsen UI. Within one of the views, there exists an array of list items where each item can be associated with a random number of radio buttons. These lists are dynamically generat ...

Executing system commands using Groovy is a breeze

One of the scripts I have is a sample.js script that allows me to view files located on the server myHost. It works perfectly: var exec = require('ssh-exec') var v_host = 'myHost' exec('ls -lh', { user: 'username&apo ...

How can I add a new property to an object type within an Interface in TypeScript?

I'm currently exploring how to merge declare an interface, with the twist of adding a property to the object literal type instead of directly to the interface itself. Within a library, I have a type that looks like this: interface DefaultSession { ...

New Trainee - Error: document has not been defined

Encountering an Error message while attempting to run Intern tests from the test files directory. The structure of the directory is as follows: test resources rest pickup.js cashManagement.js gitignore intern.js packages.js ...

Check if a certain object is devoid of any values based on the elements in an array - JavaScript

I have collected data related to various businesses: { "business": { "type": [ "LLC", "Corporation" ], "LLC": { "status": "acti ...

"Array.Find function encounters issues when unable to locate a specific string within the Array

Currently, I am utilizing an array.find function to search for the BreakdownPalletID when the itemScan value matches a SKU in the array. However, if there is no match found, my application throws a 'Cannot read property breakdownPalletID of undefined& ...

The Material-ui Drawer element is failing to display its internal items

In my current project, I am building a practice e-commerce application utilizing React.js, @material-ui/core/Drawer, and Redux. I've encountered an issue where manually rendering items to the Drawer works fine, but utilizing a handleAddToCart function ...

Ways to display a specific HTML element or tag depending on the given prop in VueJs

When working with Vue.js, it's important to remember that a <template> can only have one root element. But what should be done if you need to render different html elements based on a prop? For instance, let's say we have a <heading> ...

Troubleshooting in WebStorm: Uncovering the Root Cause Within an npm Package (node:36378) [DEP0005] - Warning: Deprecation Warning

Over the past 6 months, I've been encountering an error that seems to have surfaced after an update to node.js. (node:36378) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), ...

Error encountered while compiling a method within a .vue component due to a syntax issue

I have been closely following a tutorial on Vue.js app development from this link. The guide instructed me to add a login() function in the block of the Login.vue file. Here is the snippet of code provided: login() { fb.auth.signInWithEmailAndPa ...