Sort through a list of objects by certain properties

I'm currently dealing with two arrays: one contains displayed columns and the other contains objects retrieved from a database, with more attributes than the displayed columns.

displayedColumns = ['CompanyName','Ticker', 'Id', 'Name', 'Date', 
      'Spot', 'PreviousTradeDate', 'PreviousSpot', 'FPrice', 'Status']
 data = [ {CompanyName = "..." Ticker = "..." other attributes........}
{.......} ]

I am facing issues filtering the data array to only show the attributes and values from the displayed columns array (excluding the other attributes).

I am unsure how to achieve this using the map() function, especially when I need to filter by more than one value.

Any help would be greatly appreciated. Thank you!

Answer №1

If you wish to create a new object with specific keys from an array, you can use the map function.

var displayedColumns = ['CompanyName','Ticker', 'Id'],
    data = [{ CompanyName: 'ABC', Ticker: '123', Id: 1, x: 'foo' }, { CompanyName: 'ABD', Ticker: '124', Id: 2, x: 'bar' }];
    result = data.map(o => Object.assign(...displayedColumns.map(k => ({ [k]: o[k] }))));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To retrieve the keys for each object in the data array and verify if those keys exist in the displayedColumns or not, you can follow this example:

var displayedColumns = ['CompanyName','Ticker', 'Id', 'Name', 'Date', 
      'Spot', 'PreviousTradeDate', 'PreviousSpot', 'FPrice', 'Status'];
      
var data = [
    {
      'CompanyName': 'CompanyName1',
      'Ticker': 'Ticker1',
      'SomeRandomProperty': 'SomeRandomProperty1'
    },
    {
      'CompanyName': 'CompanyName2',
      'Ticker': 'Ticker2',
      'SomeRandomProperty': 'SomeRandomProperty2',
      'Name': 'Name1'
    },
    {
      'CompanyName': 'CompanyName3',
      'Ticker': 'Ticker3',
      'SomeRandomProperty': 'SomeRandomProperty3',
      'Name': 'Name3',
      'FPrice':'FPrice1',
      'testProperty': 'testProperty1'
    }
];
var finalObj = [];
data.forEach(function(obj){
   var keys = Object.keys(obj);
   var innerObj = {};
   keys.forEach(function(key){
     if(displayedColumns.indexOf(key) !== -1){
       innerObj[key] = obj[key];
     }
   });
   finalObj.push(innerObj);
});

console.log(finalObj);

If you want this code to be compatible with IE browser, avoid using includes() as it is not supported in IE. Also, replace arrow functions with normal 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

Tips for setting the id parameter on the asp-route-id for the modal button

My code is causing me some trouble. I have a table with 3 columns: category, subcategories and actions. In the third column, I display buttons "Edit" and "Delete". Here is a snippet of my code: <tbody> @foreach (var category in Model.ToList() ...

Guide to implementing ion-toggle for notifications with Ionic 2 and Angular 2

Currently, I am using a toggle icon to set the notification as active or inactive. The response is obtained from a GET call. In the GET call, the notification value is either 0 or 1, but in my TypeScript file, I am using noteValue as boolean, which means w ...

Tips for generating JSON data in the correct format dynamically while continuously adding new information to the existing object

In my form, users input their email and password, which then generates dynamic JSON upon submission. However, I encountered an issue where the JSON gets corrupted when logging in with different user details as it updates the existing JSON with a new object ...

Pass PHP date to JavaScript and increase its value

I'm looking to retrieve the server time with PHP and store it in a JavaScript variable. Once stored, I'd like it to continuously increment. Below is the code snippet: function initTime(date){ var today=new Date(date); var h=today.getHours(); v ...

Flow - secure actions to ensure type safety

Currently implementing flow and looking to enhance the type safety of my reducers. I stumbled upon a helpful comment proposing a solution that seems compatible with my existing codebase: https://github.com/reduxjs/redux/issues/992#issuecomment-191152574 I ...

How would you utilize jQuery to access the "option" array of a select control with the attribute of multiple=true by utilizing the find() method?

When using jquery, I am attempting to access selected items from a select control that has multiple=true. My goal is to reference them by name criteria and then iterate through the list. Below is my current code snippet: var currentRow = $(this); // sele ...

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...

The module '@angular/core' is not found in the Visual Studio Code IDE

It seems like a straightforward code. However, I am encountering the error cannot find module '@angular/core'. course.component.ts import {Component} from '@angular/core' @Component({ selector: 'courses' }) export clas ...

Determine the width of invisible images using JavaScript/jQuery

Please take a look at the jsFiddle Every time I run it, I am trying to retrieve the width of the images, but the values I get are as follows (check in the JS console) 400 0 575 533 0 ... Some values are zero, and I can't figure out why. It seem ...

Convert all page links to post requests instead

Currently, I am working on a JavaScript project where my objective is to transform all links on the page into forms. This will enable the requests to be sent using the POST method rather than the GET method. The code I have implemented so far is as follow ...

Video tag with centered image

For a current project, I am in need of rendering a centered image (a play button) at runtime on top of a video based on the UserAgent. If the userAgent is not Firefox, I want to display the image as Firefox has its own playEvent and button on top of the vi ...

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

Is Eslint functioning in just one Sublime Text project?

I have encountered an issue where I duplicated the .eslintrc and package.json files for two projects, but only the first project is able to run linting properly. The second project does not show any errors. I am using sublime-linter with the eslint modul ...

Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type. **template.html** <mat-form-field > <input matInput [matAutocomplete]="auto" [formControl]="customerFi ...

Troubleshooting: Why is the Array in Object not populated with values when passed during Angular App instantiation?

While working on my Angular application, I encountered an issue with deserializing data from an Observable into a custom object array. Despite successfully mapping most fields, one particular field named "listOffices" always appears as an empty array ([]). ...

Tips for invoking the export function in node.js using sequelize

Need help with calling the function (search_all_user) to export in node.js using sequelize module.exports = function (sequelize, Sequelize, DataTypes) { var User = sequelize.define('user', { id: {type: Sequelize.INTEGER, unique: true, prima ...

Managing numerous HTTP requests and subscribing at the conclusion in Angular 4

I am facing an issue with Angular 4 that I need help resolving. The problem arises when I have to make multiple http calls to fetch data. The number of calls depends on a prior response which provides a list of items to process. I need to concatenate all ...

Tips for dynamically hiding/showing a button depending on the focus of two different HTML inputs

I'm working on a login section and looking to add a unique feature: When a user selects the email or password input field, I want the button text to change to 'LOGIN'. If neither input field is selected, the text should display 'NOT A ...

Set up a personalized React component library with Material-UI integration by installing it as a private NPM package

I have been attempting to install the "Material-UI" library into my own private component library, which is an NPM package built with TypeScript. I have customized some of the MUI components and imported them into another application from my package. Howe ...

Angular Form Required not functioning as expected

I have encountered an issue with my form where the required attribute does not seem to work properly. Even when I leave the input field empty, the form still gets submitted. Here is a snippet of my code: <div class="form-group"> <div class="c ...