What is the best way to filter an array of objects using an array of strings?

Suppose we have an array filled with objects :

people = [
    {id: "1", name: "abc", gender: "m", age:"15", country:"USA" },
    {id: "2", name: "def", gender: "m", age:"25", country:"BRA" },
    {id: "3", name: "ghi", gender: "f", age:"05", country:"CHI" },
    {id: "4", name: "jkl", gender: "m", age:"35", country:"RUS" },
    {id: "5", name: "mno", gender: "m", age:"41", country:"JAP" },
    {id: "6", name: "pqr", gender: "f", age:"30", country:"COL" },
    {id: "7", name: "stu", gender: "f", age:"31", country:"CAN" },
    {id: "8", name: "vwx", gender: "m", age:"78", country:"USA" },
]

As well as an array containing the keys of interest:

wantedKeys = ["name", "age", "country"]

Desired outcome:

peopleFiltered = [
    {name: "abc", age:"15", country:"USA" },
    {name: "def", age:"25", country:"BRA" },
    {name: "ghi", age:"05", country:"CHI" },
    {name: "jkl", age:"35", country:"RUS" },
    {name: "mno", age:"41", country:"JAP" },
    {name: "pqr", age:"30", country:"COL" },
    {name: "stu", age:"31", country:"CAN" },
    {name: "vwx", age:"78", country:"USA" },
]

How can we filter the people array to generate a new array with only the elements specified in the wantedKeys array?

Answer №1

Solution

If you're looking for a more concise solution, you can try using the reduce method. However, the current code serves as a good starting point.

var peopleFiltered = people.map(person => {
  var obj = {};
  wantedKeys.forEach((key) => obj[key] = person[key]);
  return obj;
});

Interactive Demo

people = [{
    id: "1",
    name: "abc",
    gender: "m",
    age: "15",
    country: "USA"
  },
  {
    id: "2",
    name: "def",
    gender: "m",
    age: "25",
    country: "BRA"
  },
  {
    id: "3",
    name: "ghi",
    gender: "f",
    age: "05",
    country: "CHI"
  },
  {
    id: "4",
    name: "jkl",
    gender: "m",
    age: "35",
    country: "RUS"
  },
  {
    id: "5",
    name: "mno",
    gender: "m",
    age: "41",
    country: "JAP"
  },
  {
    id: "6",
    name: "pqr",
    gender: "f",
    age: "30",
    country: "COL"
  },
  {
    id: "7",
    name: "stu",
    gender: "f",
    age: "31",
    country: "CAN"
  },
  {
    id: "8",
    name: "vwx",
    gender: "m",
    age: "78",
    country: "USA"
  },
]

wantedKeys = ["name", "age", "country"]

var peopleFiltered = people.map(person => {
  var obj = {};
  wantedKeys.forEach((key) => obj[key] = person[key]);
  return obj;
});

console.log(peopleFiltered);

Answer №2

Utilizing the powerful lodash function called pick, we can achieve the desired outcome by combining it with Array.map():

people = [ {id: "1", name: "abc", gender: "m", age:"15", country:"USA" }, {id: "2", name: "def", gender: "m", age:"25", country:"BRA" }, {id: "3", name: "ghi", gender: "f", age:"05", country:"CHI" }, {id: "4", name: "jkl", gender: "m", age:"35", country:"RUS" }, {id: "5", name: "mno", gender: "m", age:"41", country:"JAP" }, {id: "6", name: "pqr", gender: "f", age:"30", country:"COL" }, {id: "7", name: "stu", gender: "f", age:"31", country:"CAN" }, {id: "8", name: "vwx", gender: "m", age:"78", country:"USA" }, ]

wantedKeys = ["name", "age", "country"];

let result = people.map(p => _.pick(p, wantedKeys));
console.log('Result:');
result.forEach(r => console.log(JSON.stringify(r)))
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" referrerpolicy="no-referrer"></script>

For those preferring a vanilla JavaScript method, employ Object.fromEntries() along with Array.map():

people = [ {id: "1", name: "abc", gender: "m", age:"15", country:"USA" }, {id: "2", name: "def", gender: "m", age:"25", country:"BRA" }, {id: "3", name: "ghi", gender: "f", age:"05", country:"CHI" }, {id: "4", name: "jkl", gender: "m", age:"35", country:"RUS" }, {id: "5", name: "mno", gender: "m", age:"41", country:"JAP" }, {id: "6", name: "pqr", gender: "f", age:"30", country:"COL" }, {id: "7", name: "stu", gender: "f", age:"31", country:"CAN" }, {id: "8", name: "vwx", gender: "m", age:"78", country:"USA" }, ]
 
wantedKeys = ["name", "age", "country"];
let result = people.map(p => Object.fromEntries(wantedKeys.map(k => [k,p[k]])));
console.log('Result:');
result.forEach(r => console.log(JSON.stringify(r)))
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

Uploading files with previews and no option to alter the image dimensions

I am having trouble with resizing an image preview before submitting it. Despite setting the width and height to 1px in both the div and image, it still displays at its normal dimensions. $(function() { var imagesPreview = function(input, placeToIns ...

Struggling to Retrieve Specific Keys for Individual Values in Firebase with React Native

I am currently experiencing difficulty obtaining a unique key for each value in the 'users1' table. firebase.database().ref('users1').once('value').then(snapshot => { var items = []; snapshot.forEach((child) => { ...

"Update data on a webpage using Javascript without the need to refresh the

I encountered a problem with my code for posting messages in the "chatbox". When I include return false; at the end of the function, the data is not submitted. However, if I remove it, the data submits successfully. JavaScript Code function dopost() { ...

The serialization method in ajax is not providing the expected values as needed

Having trouble retrieving all the necessary form inputs using AJAX, jQuery, and Bootstrap modal. The serialize method is not returning all the required values. Specifically, I am missing the user_id and btn_action values. What could be the issue? I'v ...

Using JavaScript to create an image slider

My image slideshow with prototyping is not working properly and I am struggling to fix it. I have tried binding the setInterval function but it's not working. I also attempted to wrap it, but that didn't work either. What should I do to solve thi ...

Ensure each list item is directly aligned when swiping on a mobile device

Looking to make a simple horizontal list swipeable on mobile devices with tabs that snap from tab to tab, activating the content for the active tab immediately. The desired effect is to swipe directly from one tab to the next without having to click separ ...

How can I fill arrays in python using numpy?

Imagine having a file structured in the following way: a a 0 a b 1 a c 1 b b 0 b a 1 b c 1 c c 0 c a 1 c b 1 The third column represents the distance between the items in the first and second columns. If I were to import this file into Python as a nested ...

There seems to be an issue with Bookshelfjs and bcrypt hashPassword - it is functioning properly during the create

When using bcrypt to hash passwords in bookshelfjs, I encountered an issue where the password was not being hashed when attempting to update it. Here is the code snippet: model.js var Bookshelf = require('../../db').bookshelf; var bcrypt = requ ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Javascript and JSON: Making Updates to Files

Working on a program, I am faced with an issue while sending a literal variable to local storage using JSON.stringify. My goal is to continuously update the local storage and append to the existing data stored. The problem arises during the parsing of the ...

I desire to activate the textbox only when the radiobtnlist value equals 1

I am trying to disable a textbox based on the selected value of a RadioButtonList in my code. However, the functionality is not working as expected and I am unsure why. <script type="text/javascript"> $(function () { $("#RadioButton ...

Text field in React's material-ui causes the screen to shake

I am encountering an issue with a simple React code that includes a Material-UI Textfield. Whenever I try to enter data into the text field, the screen shakes. Additionally, when I click outside of the box after entering data, the screen shakes again. Ca ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...

How can two unique links toggle the visibility of divs with two specific IDs?

I am developing an interactive questionnaire that functions like a 'create your own adventure' story. The questions are shown or hidden depending on the user's responses. Below is the HTML code: <!-- TIER 3 ============================== ...

Locating the Maximum and Minimum Values in an Array yields a result of zero

I need to create an array, initialize it, and then write two helper methods. One method should find the maximum value in the array and the other should find the minimum value. However, when I run the code, both methods are returning 0. Here is the code I ...

I am facing an issue with body-parser not properly processing my request in express.js

Utilizing the Controller in my project. Snippet from app.js: var express = require('express'); var app = express(); const routes = require('./Routes/route'); const bodyParser = require('body-parser'); app.use('/', ...

Creating new 'morphing' geometry in Three.js with all required buffers: A step-by-step guide

I have implemented a web-worker to load a .json file that contains an animated 3D model. To optimize performance, I am transferring Float32Array buffers for the main arrays (vertices, normals, etc.) back to the UI thread, leveraging the benefits of transfe ...

Encountering Babel issues while incorporating npm package into React Native project

Currently, I am developing a React Native application. In an attempt to enhance my application, I decided to incorporate the npm package available at this link: https://github.com/MagicTheGathering/mtg-sdk-javascript/ Despite trying various import statem ...

Using jQuery to access a server-side SQL database through PHP

After searching for an example on connecting a client to a server's SQL database using JQuery, AJAX, and PHP, I came across this seemingly well-executed guide: Example Link. All my PHP files and the jQuery library (javascript-1.10.2.min.js) are contai ...