How to Filter Specific Keys in Nested JavaScript Arrays

I'm working with a JavaScript Array and I'm looking to filter it to only include certain keys:

function cleanArray(arr, whitelist) {
  // remove all non-whitelisted keys from the array
}

let origArr = [
  { keep1: 'abc', keep2: 'def', buh1: false, buh2: false },
  { keep3: 'abc', keep4: 'def', buh3: false, buh4: true },
  { keep5: 'abc', keep6: 'def', buh5: false, buh5: false }
];

let whiteList = ['keep1', 'keep2', 'keep3', 'keep4', 'keep5'];
let resultArr = cleanArray(origArr, whiteList);

// expected output
resultArr = [
  { keep1: 'abc', keep2: 'def' },
  { keep3: 'abc', keep4: 'def' },
  { keep5: 'abc', keep6: 'def' } 
];

How can I go about removing all non-white-listed keys from this Array without simply iterating through it? It doesn't have to be immutable; readability is key here.

Thanks for your suggestions!

Answer №1

Here is a solved example:

let data = [
  { name: 'John', age: 25, city: 'New York', isActive: true },
  { name: 'Lisa', age: 30, city: 'Los Angeles', isActive: false },
  { name: 'Mike', age: 35, city: 'Chicago', isActive: true }
]

let filterList = ['name', 'age'];

data.forEach(function (person) {
  Object.keys(person).forEach(function(key) {
    if (filterList.indexOf(key) == -1) 
      delete person[key]
  })
})

console.log(data)

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

Refreshing AngularJs screens via polling

I have a list of devices that require regular updates to monitor their display. I've set the poll interval to 15,000ms. However, every time the list is updated, there is a quick flicker and the user is taken back to the top of the list. Is there a way ...

What causes Chrome to automatically remove a script tag?

Hello everyone! Instead of utilizing jQuery, I have been creating a script tag and appending it to the head tag in order to retrieve JSONP data. However, after the JSONP callback function is executed, I have noticed that the script tag that I added to the ...

Could you explain the purpose of the app.use(cors()) function call?

I'm aware that accessing an API with a different domain than our own is not allowed. Nonetheless, I often observe individuals incorporating the cors module into their Express.js applications in order to interact with APIs and then utilizing it in this ...

The height of the browser action will not return to its original state

I'm currently working on an extension that provides responses based on user text input. However, I'm running into an issue where the height of the browser action won't reset properly. I've tried various methods to fix this problem, in ...

Using cfajaxproxy in conjunction with URL rewriting capabilities

I have successfully integrated the cfajaxproxy tag, but encountered an issue with the cfc's location in the root directory of my site. When accessing a page within the root directory through a rewritten URL (e.g. mysite.com/one/two/ -> mysite.com/ ...

Having trouble with Node.js code not behaving as anticipated and adding the object twice in the array?

I'm currently working on creating a Blog Website, and I'm facing an issue with the app.post("/compose", function() {}) line. When I push the user's data object into the globally defined array named posts and then console.log the ar ...

Unable to store the user's input information in the database

I've been attempting to incorporate an "add" button feature that saves/adds/inserts data into my table. I have inputted some text in the form of tags (input type), but unfortunately, it doesn't seem to be functioning properly. Despite conducting ...

Troubles with Angular elements not aligning correctly when using the "display: block" property

When using an angular element for a directive with "display: block", it may not automatically take up 100% of the width of the parent container. In order to ensure that it does, the width must be explicitly set to "100%" in the CSS. Despite setting "width: ...

Adjusting the dimensions of a unicode character or image with Javascript or jQuery

I am facing a challenge with a dynamically changing table. Depending on a specific condition, I need to display different images - one if the condition is met and another if it isn't. Initially, I tried using Unicode characters, but they were too sma ...

employ variables as booleans within pug

Utilizing pug within nodejs requires passing boolean locals to pug files for conditional logic. How can I incorporate the firstnameProblem variable into an if condition within a pug file as shown below? email.js: email.send({ template: template, ...

Initiate requests to external servers from a NodeJS backend

My NextJS application seamlessly collaborates with a NodeJS server to act as the front end of my innovative three-tier architecture. 'use client'; import FormControl from '@mui/material/FormControl'; import InputLabel from '@mui/m ...

I am looking for the best way to pass a JSON value to another method

I have a scenario where I am fetching a JSON response from an API and need to pass that data to another method for insertion into a database. HttpClient client = HttpClientBuilder.create().build(); HttpGet request=new HttpGet("/2.0/clusters/list" ...

I am attempting to retrieve the information entered into the textbox, search for it within my database, and display the results beneath the textbox for reference

<!----- fetchCedulaData.php This script retrieves data from the database and performs a search to return results ---------------------------- - --> <?php require("connection.php"); $cedula=$_REQUEST["cedula"]; //$cedula="0922615646"; echo $cedu ...

Issue with responsive canvas height in Particle-JS

Recently, I've been working on a Bootstrap portfolio where I am experimenting with implementing particle.js over a profile picture. I placed the particles inside a DIV and set a background image as the profile photo. The issue arises when I reload th ...

Encountering an issue where rendering a component named Exercise within the ExerciseList component is not allowed

The ExerciseList component is designed to display all the exercises that can be edited or deleted from the list. It returns the Exercise Component or function for this purpose. If anyone could take a look and help identify any mistakes in my code, it would ...

Creating an array of multiple recipients through Mandrill: A step-by-step guide

I am looking for a way to send emails to multiple recipients, with the number of recipients varying based on data in the database. Mandrill only allows me to add multiple recipients using an array. Below is the code that works for multiple recipients: / ...

The functionality of Firebase storage.object().onChange has been removed and is no longer supported

Trying to implement a trigger to resize an image after uploading it to Firebase database, but encountering an error message: Error: "onChange" is now deprecated, please use "onArchive", "onDelete", "onFinalize", or "onMetadataUpdate". at ObjectBuilde ...

Bootstrap.js has the ability to utilize nested objects for organizing and

As I work on enhancing a Combobox class I developed to complement Bootstrap 4, I am aiming to align the Javascript with the existing Bootstrap code. During this process, I came across a snippet of code in bootstrap.js while studying the Modal component: ...

Discover the magic of using jQuery's .map() method with

$(function() { $('input[type=checkbox]:checked').map(function() { alert($("#chk_option").val()); $("#chk_option").val(this.value); }).get(); }); HTML code <div> <center> <form id="form_tarif" class="form-horizo ...

Save the environment value within Vue when the app starts up

When working with a basic web app created using VueJS, the application makes an API call that returns an object containing the environment name. For instance: https://appsdev/mysimpleapp/api/environment returns {"applicationName":"My S ...