Guide to sorting data by the status value within a JavaScript object?

I have a JavaScript object structured like this:

{
  "3": {
    "id": 3,
    "first": "Lisa",
    "last": "Morgan",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd7d6d4c9dcdad5fbdcd6dad2d795d8d4d6">[email protected]</a>",
    "phone": "(508) 233-8908",
    "status": 0
  },
  "4": {
    "id": 4,
    "first": "Dave",
    "last": "Hart",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14707c756660547379757d783a777b79">[email protected]</a>",
    "phone": "(509) 874-9411",
    "status": 1
  }
}

I am interested in filtering the object to extract records with a status value of '1'. One way I can achieve this is by using array filter as shown in the code snippet below:

var filterJSON = Object.values(obj).filter(function (entry) {
                switch(frmFilter){
                    case '1':
                        return entry.status === 1;
                        break;
                    case '2':
                        return entry.status === 0;
                        break;
                    default:
                        return entry;
                }
            });

The issue with this approach is that it converts the filtered data into an array. I want to maintain the structure of my data as an object, similar to the original format before applying the filter. Is there a method to filter through the object while preserving its object type and achieving the same output as filtering through an array?

Answer №1

Utilizing .filter() along with .reduce() enables you to transform the filtered array into an object:

var obj = {
  "3": {
    "id": 3,
    "first": "Lisa",
    "last": "Morgan",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7519181a0712141b351218141c195b161a18">[email protected]</a>",
    "phone": "(508) 233-8908",
    "status": 0
  },
  "4": {
    "id": 4,
    "first": "Dave",
    "last": "Hart",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2e222b383e0a2d272b232664292527">[email protected]</a>",
    "phone": "(509) 874-9411",
    "status": 1
  }
}

var frmFilter = "1";

var filterJSON = Object.keys(obj).filter(function (key) {
    let entry = obj[key];
    switch(frmFilter){
        case '1':
            return entry.status === 1;
            break;
        case '2':
            return entry.status === 0;
            break;
        default:
            return entry;
    }
}).reduce( (res, key) => (res[key] = obj[key], res), {} );

console.log(filterJSON);

This solution was inspired by: JavaScript: filter() for Objects

Answer №2

Give this a shot:

const info = {
  "3": {
    "id": 3,
    "first": "Lisa",
    "last": "Morgan",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec2c3c1dcc9cfc0eec9c3cfc7c280cdc1c3">[email protected]</a>",
    "phone": "(508) 233-8908",
    "status": 0
  },
  "4": {
    "id": 4,
    "first": "Dave",
    "last": "Hart",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfdbd7decdcbffd8d2ded6d391dcd0d2">[email protected]</a>",
    "phone": "(509) 874-9411",
    "status": 1
  }
};

const filteredData = Object.values(info).filter(item => item.status == 1);
const result = {};
filteredData.forEach(item => result[item.id] = item);
console.log(result);

Answer №3

When utilizing the filter Array function, it will yield a plain array instead of an object resembling the original (obj)

To achieve this, you can iterate through each property and copy/modify them into a new object:

var filteredObject = {};
for (var property in obj) {
  if (obj.hasOwnProperty(property)){

        switch(filterType){
                case '1':
                    if (filteredObject[property].status == 1){
                       filteredObject[property] = obj[property];
                    } 
                    break;
                case '2':
                    if (filteredObject[property].status == 0){
                       filteredObject[property] = obj[property];
                    }
                    break;
         }
   }
}

Answer №4

Your search ends here:

const filterFunction = (data, condition) => {
  return Object.keys(data).reduce((accumulator, currentKey) => {
    if (condition(data[currentKey])) {
      accumulator[currentKey] = data[currentKey];
    }
    return accumulator;
  }, {});
}

// result includes only items with status set to 1
const result = filterFunction(data, (item) => item.status === 1);

// result2 includes only items with last name longer than 4 characters
const result2 = filterFunction(data, (item) => item.last.length > 4);

The condition function is applied to each item, and if it returns true, the item is added to the result.

Answer №5

I explained the for...in loop in JavaScript, which is commonly used to loop through the properties of an object.

Check out this link for more information on for...in loops in JavaScript.

var obj = {
  "3": {
    "id": 3,
    "first": "Lisa",
    "last": "Morgan",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7bbbab8a5b0b6b997b0bab6bebbf9b4b8ba">[email protected]</a>",
    "phone": "(508) 233-8908",
    "status": 0
  },
  "4": {
    "id": 4,
    "first": "Dave",
    "last": "Hart",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3979b928187b3949e929a9fdd909c9e">[email protected]</a>",
    "phone": "(509) 874-9411",
    "status": 1
  }
}
var filteredObj = {};
for (var props in obj){
  if(obj[props].status===1)
  filteredObj[props] = obj[props] ; 
  }
  
  console.log(filteredObj)

This code snippet demonstrates how to iterate over the properties of an object and filter based on a specific condition.

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

Using Angular and Firestore to push matched properties into an array

Module 1 this.service.myArray['bands'] = data; Module 2 Module two is designed to receive artist IDs individually through an @Input attribute. Following that, a query is executed to retrieve all relevant albums. Each album entry includes an &ap ...

Having trouble retrieving the URL from JSON data - every time I attempt to access it, it just shows as undefined. Any suggestions

Having trouble extracting the URL from JSON, as it shows undefined. Any suggestions? <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <script language="JavaScript" type="text/javascript" ...

Having issues with closing a div tag using $.after() function

This issue can be better understood with an example: http://jsbin.com/lavonexuse The challenge here is to insert a full-width row after a specific column (identified by the class .insertion-point) when "Insert Row" is clicked. The problem I'm facing ...

Error: Trying to access the 'title' property of an undefined variable in Vue.js

Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...

A guide on updating the value of a two-dimensional array using the useState() hook

Take a look at this Codesandbox example demonstrating my issue. Experiment by typing some words into both text areas to observe the problem. I have just started learning React. My goal is to dynamically generate an svg element based on user input. I am br ...

Utilizing d3.json: changing the URL with dynamic data

Just getting started with d3 and building a sankey diagram. I came across a sample that uses an external .json file with d3.v3, even though it is an outdated version. Since my tree also relies on this version, I'd like to stick to just one d3 version. ...

Execute a function when the selected option changes

Now I have implemented a code that dynamically changes the foreign key based on user input and retrieves data accordingly. Here is how it all comes together: Starting with the HTML page: <div class="large-6 columns"> {% csrf_token %} <in ...

Retrieving data from a subcollection in a cloud firestore database does not yield any results

In my Next.js application, I am utilizing Cloud Firestore database to store user documents. The structure of the collection path is as follows: collection "userDocs" └─ document "userEmail" └─ collection "docs" └─ document "document ...

Checking an array of objects for validation using class-validator in Nest.js

I am working with NestJS and class-validator to validate an array of objects in the following format: [ {gameId: 1, numbers: [1, 2, 3, 5, 6]}, {gameId: 2, numbers: [5, 6, 3, 5, 8]} ] This is my resolver function: createBet(@Args('createBetInp ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

What is the most effective way to compare two arrays of objects in JavaScript?

I'm working on a function that needs to return an array of elements based on certain filters. Here is the code for the function: filter_getCustomFilterItems(filterNameToSearch: string, appliedFilters: Array<any>) { let tempFilterArray = []; ...

creating interconnections between input fields by employing event listeners in JavaScript

I've been experimenting with binding multiple input fields to a span element using jQuery. Specifically, I have two input fields containing integer values and the sum of these values is displayed in a span element. I want the span element to update wh ...

Filter an object from a list using Flutter and Dart

I am looking to filter a List using a Button String. I have a Content List like this, var activeList = []; List<Subjects> contentList = [ Subjects("TYT", "Turkish-TYT", "Word Meaning", "https://youtube.com"), Subjects("TYT", "Mat ...

The HTML button triggers a function to execute on a different webpage when clicked

I'm facing a straightforward issue that I can't seem to figure out due to my limited experience with Angular and web development. The problem revolves around two components, namely home and dashboard. In the home.component.html file, there's ...

What is the process for invoking a websocket from an HTML client?

I have created a WCF Service using netHttpBinding binding and it is hosted on IIS 8 (Windows Server 2012). The interfaces for the service are as follows: [ServiceContract(CallbackContract = typeof(IDuplexCallbackContract))] public interface IHelloWebSocke ...

Displaying elements of an array in a textView in Swift

Is there a way to incorporate all the items from an array into a textView with a slight time delay of 1 second? Using the swift programming language. (I am still in the early stages of learning programming) ...

The error 'NSInvalidArgumentException' is being caused by an invalid data type (_SwiftValue) when trying to write JSON with Alamofire in Swift3

When trying to upload Swift3 using XCode8, I've come across the following error. 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)' let param: Parameters = [ "email":txrNRC.text as AnyObject ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

In JavaScript, filter out an array of image links that end with .jpg, .jpeg, .png, or

Need assistance, could someone lend a hand? I've got an array of image URLs and I'm attempting to filter out only the links with supported images using regex or endsWith(). It's been a struggle all morning. Appreciate any help offered! ...

Tips for customizing the AjaxComplete function for individual ajax calls

I need help figuring out how to display various loading symbols depending on the ajax call on my website. Currently, I only have a default loading symbol that appears in a fixed window at the center of the screen. The issue arises because I have multiple ...