Filter out items from an array in JSON that are not included in a separate array, utilizing TypeScript

Is there a way to remove objects from a JSON array that are not included in another array?

let originalArray = [{
  id: 1,
  NoOfEmp: 12,
  Wages:1000,
  TotalSI: 21,
  Salary:3000
}, {
   id: 2,
  NoOfEmp: 13,
  Wages:2000,
  TotalSI: 22,
  Salary:4000
}]

let keepArrayObjects = ['id','NoOfEmp','Wages']

originalArray = originalArray.filter( function( el ) {
  return keepArrayObjects.indexOf( el ) >  0;
} );

console.log(originalArray); 

The code above was an attempt to remove the "TotalSI" and "Salary" objects, while keeping those listed in the keepArrayObjects array. However, it did not work as expected.

I am looking to modify the original array itself. Can someone provide assistance with this?

Answer №1

You have the option to create new objects by mapping desired entries.

let array = [{ id: 1, NoOfEmp: 12, Wages: 1000, TotalSI: 21, Salary: 3000 }, { id: 2, NoOfEmp: 13, Wages: 2000, TotalSI: 22,  Salary: 4000 }],
    keys = ['id', 'NoOfEmp', 'Wages'],
    result = array.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

For Internet Explorer compatibility:

var array = [{ id: 1, NoOfEmp: 12, Wages: 1000, TotalSI: 21, Salary: 3000 }, { id: 2, NoOfEmp: 13, Wages: 2000, TotalSI: 22,  Salary: 4000 }],
    keys = ['id', 'NoOfEmp', 'Wages'],
    result = array.map(function (source) {
        return keys.reduce(function (target, k) {
            target[k] = source[k];
            return target;
        }, {});
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you're looking to eliminate certain properties from an object:

sourceArray.filter((item) => {
  for (let property in item) {
    if (!propertiesToKeep.includes(property)) {
      delete item[property]
    }
  }
});

console.log(sourceArray);

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

Navigating to User's Specific Info Page using Node.js

Would love some input on my current issue. I have a table featuring a list of users, and my goal is to display user information in detail whenever a user (which corresponds to a row in the table) is clicked. The process involves identifying which user was ...

What is the best way to merge append() and replaceWith() functions in jQuery?

Is there a way in Jquery to merge the functions of append() and replaceWith()? In my JQM project, I have a login form that appears on every page. Since multiple pages are loaded into the DOM, I need to shift the form along as the user navigates through th ...

Using directive to access service values directly

I am in need of utilizing a directive to fetch and display data using ng-repeat from a service. The anticipated result will be <ul>Days <li>Monday</li> <li>Tuesday</li> ... <ul> <ul>Month <li>January</li ...

How do you retrieve the font-size value in percentages using jQuery's `css()` method for the element `e`?

When using the $(e).css('font-size')) method, how can I retrieve the font size as it appears (100% in my example)? It currently returns it as 100% of 16px which equals to 16px. jQuery ( function($) { alert($('div').css(&ap ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

What is the method for closing an <iframe> element directly?

A web page called room.html contains a table with an onclick function named place(): function place() var x = document.createElement("IFRAME"); x.setAttribute("src", "loading.html"); document.body.appendChild(x); } What is ...

using configureStore instead of createStore

After updating my packages, I received a notification from VScode indicating that the createStore function was deprecated. This prompted me to go ahead and replace it with the recommended alternative. In my store file, I left the original line as a commen ...

The error message states: "An error occurred: Unable to find the 'HttpProvider' property within an undefined

import * as Web3 from 'web3' import { OpenSeaPort, Network } from 'opensea-js' const provider = new Web3.providers.HttpProvider('https://mainnet.infura.io') Hello everyone, I'm currently learning Node.js and encountered ...

Remove chosen tags from the options list in Material UI Autocomplete Multiple

When utilizing the Material UI Autocomplete for multiple values, the selected input is shown in the options list with a blue background color. Is there a way to configure the autocomplete to exclude already selected values from appearing in the options li ...

Unresolved (waiting for response) unidentified

I encountered a perplexing error in Chrome and I am unable to identify its source: https://i.sstatic.net/f9Blt.png The only clue I have is that after refactoring approximately 10,000 lines of code, this error surfaced. It occurred during the middle of the ...

Tips for updating the font size of your MUI Accordion title

I was attempting to adjust the font size of the MUI-5 Accordion title. It seems like I need to override it, but I am unsure about how to do so with CSS in MUI-5. Instead of 'SX', it uses 'htmlSx'. When I tried using it, it did not produ ...

Filter an array containing nested objects based on dynamically determined properties

I'm working with an array of N objects and need to create a filter using JSON.stringify that dynamically checks multiple properties. Looking for a solution that is dynamic and doesn't rely on static properties (as shown in the code snippet above ...

What are some ways to optimize Ajax requests for improved speed when multiple identical requests are made on a single webpage?

When the webpage is loaded, a block is dynamically created using an Ajax call to retrieve data from another page. This structure is then populated and added to a specific DOM element. However, multiple Ajax calls during page loads are causing delays. Is ...

Filtering data from an Ajax request in Angular using a filter function with JSON

Hi everyone, I recently started learning AngularJS and created a basic item list with search functionality and pagination. Everything was working smoothly, so I decided to move my list outside the controller and store it as a JSON file. Here's what ...

Leverage PHP to dynamically populate a chart.js visualization with information sourced from an SQLite Database

I'm attempting to use chart.js to display data from an SQLite database using PHP, but I've been running into issues. Despite following multiple online tutorials, my graph remains empty or disappears altogether. This is my first time working with ...

Two separate entities link to a shared occurrence

Two namespaces are at play here: '/' and /notification If I trigger an event in the '/' namespace, how can I listen to the same event in the '/notification' namespace? It would be helpful if someone could provide an explanati ...

Placing a div with position:absolute inside another div with position:absolute and turning them into position:fixed

HTML <div class="box1"></div> <div class="box2"> <div class="box3"></div> </div> CSS Properties of box1, box2 and box3 are: box1 { position: absolute; z-index: 100; background-color: rgba(39, 39, 39, 0.3) ...

Choosing an option from a dropdown menu in Google Forms using Puppeteer in NodeJS

Hey everyone, I've been working on automating a Google form and I'm facing an issue with a dropdown menu. I'm struggling to select the desired value from the dropdown list. When I use Puppeteer to type in "United space Kingdom," it autocomp ...

django ajax request returning a 403 error

While attempting to compile project https://github.com/kannan4k/django-carpool, I encountered an error during an ajax call. The error message displayed was: "Failed to load resource: the server responded with a status of 400 (BAD REQUEST)." I suspect that ...

MatDialog displaying no content

I found this tutorial on how to implement a simple dialog. The issue I'm facing is that the dialog appears empty with no errors in the console. Even after making changes to my dialog.component.html or dress-form.ts, nothing seems to reflect in the o ...