The combination of Array map and reduce results in an unexpected undefined output

I have a pair of arrays known as headersMap and selected_arr structured in the following manner:

headersMap: [
    {
      text: "#",
      align: "center",
      sortable: true,
      value: "id",
      align: "start",
      width: "1%",
    },
    {
      text: "Name",
      align: "center",
      sortable: true,
      value: "name",
      align: "start",
    },
    {
      text: "Company",
      align: "center",
      sortable: true,
      value: "company",
      align: "start",
    }
 ]
selected_arr: ['id', 'company']

This is what I attempted:

let jsonObject = this.headersMap;
let selectedArray = this.selected_arr;
let filteredJsonObject = jsonObject.map(function(entry) {
    return selectedArray.reduce(function(res, key) {
        res[key] = entry[key];
        return res;
    }, {});
});

console.log(filteredJsonObject);

The output was:

[
    {
      #: undefined
      company: undefined
    }
]

QUESTION: My goal is to trim down the headersMap based on selected_arr, resulting in the following output:

[
    {
      text: "#",
      align: "center",
      sortable: true,
      value: "id",
      align: "start",
      width: "1%",
    },
    {
      text: "Company",
      align: "center",
      sortable: true,
      value: "company",
      align: "start",
    }
 ]

Answer №1

Utilize the Array#filter method:

const 
  data = [
    { name: "John", age: 25 },
    { name: "Jane", age: 30 },
    { name: "Tom", age: 22 }
  ],
  selectedNames = ['John', 'Jane'];

const filteredData = data.filter(({ name }) => selectedNames.includes(name));

console.log(filteredData);

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

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

What are the risks of using react + bootstrap without importing bootstrap.js?

When bootstrap library is used along with React, potential unpredictable behavior and difficult bugs may arise due to DOM modifications. Is it feasible to use bootstrap without including bootstrap.js? What are the drawbacks? While I am aware of the ' ...

Strange behavior observed when resizing objects in Three.js WebGl

Everything was going smoothly with my code until I decided to enable WebGL. It seems that the function responsible for resizing my object every frame rate stopped working. function animate(){ window.requestAnimationFrame(animate); s.setPositio ...

Modifying the content within a DIV element

I want to make changes to my DIV. <div id="main"> <div id="one"> <div class="red"> ... </div> <img class="avatar" src="img/avatar1.jpg"/> <span class="name"> John < ...

AngularJS is encountering an issue where it cannot locate the App Module

Whenever I attempt to execute this code, I encounter errors. Below is the code followed by the error message: index.html: <!DOCTYPE html> <html> <head> <meta id="meta" name="viewport" content="width=device-width, initial-scale=1 ...

The collection of elements from another component in React is failing to display in a list format

I am encountering an issue while trying to map an array of objects that I imported from a different component. The error message displayed is: Warning: Each child in a list should have a unique "key" prop. along with the following error details: Pleas ...

What is the best way to insert a string into a JavaScript variable and display other variables within it?

When working with a JSON object in JavaScript, I encountered a challenge in displaying values within the looped string and then incorporating it into my JS file. In PHP, the following syntax is typically used: $var = 'This is a '.$variable.&apo ...

What are some effective ways to analyze jQuery and JavaScript using web development tools?

I'm struggling to use web development tools to inspect the JavaScript on websites. It's challenging to identify which parts of a site are utilizing JS, unlike CSS or HTML where it's more visibly defined. Even when I attempt to delete some J ...

Check for criteria in database collection and send notification via email if requirements are satisfied || Utilizing MongoDB with

I have a scenario where I need to iterate through each element in the database and: if an element has the bumped field set to false and the creation date is less than 30 days ago then: update the bumped field to true send an email to the user! My ap ...

Please ensure that the form is only submitted when at least one checkbox is selected by utilizing JavaScript

When I visit the following form: Upon filling out the details and clicking submit, if I forget to check a checkbox, a prompt appears stating "please select any one checkbox" with an 'ok' button. After clicking 'ok', the form is then su ...

Is it possible to obtain a Node.js backend code build? If so, what is the process of acquiring a Node.js build using npm?

I am currently working on a Node.js API service application and I wish to keep my code confidential from the client. I am looking for guidance on how to create a build similar to React or Ionic in Node.js. Any suggestions on how I can achieve this would ...

Tips for verifying the data passed to a Vue component

Creating a subclassed Vue component can be done in the following way: let myApp = new MyApp({ el: '#app', data: { message: 'Hello Vue!', seconds: 0 }, created() { setInterval(() => { ...

Does MongoDB have an equivalent to prepared statements in PHP for enhancing security measures?

As I delve into learning mongodb, a pressing question arises. Does mongodb have security features similar to those found in PHP? In PHP, one could utilize the following code: $stmt = $this->conn->prepare("UPDATE news SET shown = shown+1 WHERE ne ...

How can I swap out the text within an anchor tag using jQuery?

I am working with the following HTML structure: <div class="event tiny"> <a href="/whatever">Something</a> </div> My goal is to change the text of this link to "Anything" … However, when I try the following code: $('. ...

Trouble displaying Bar Graph in chart.js using PHP

I am facing a challenge with creating a bar graph using chart.js that loads data from a PHP array via ajax. The data is successfully loaded through ajax, as confirmed in the console, but I am unable to display it on the graph. Here's what I see in the ...

Using Vuejs to import images from local storage

After selecting an image for upload by clicking on "Choose file," the path appears first and the image is only uploaded after clicking on "Choose file" again. Is there a way to resolve this issue and upload the file as soon as it is chosen? Any assistanc ...

The array is displaying only the initial value upon comparison

Looking for a solution to compare values in an array received from a post request. Here's what I have tried: Example: if ($q->param('tradesFour[]') =~ m/Steel/) The array data is as follows: 'tradesFour[]' => [ 'S ...

Creating a dynamic two-player chess application using Django - requiring the player's chess board to automatically update whenever the opponent makes a move

I am looking for a solution where each player has their own webpage equipped with a Javascript chessboard GUI interface that allows them to click and drag pieces. The challenge is ensuring that when one player makes a move, the other player's chessboa ...

Using TypeScript to test a Vue3 component that includes a slot with Cypress

I'm currently facing challenges setting up a new project. The technologies I am using include Vue3, TypeScript, and Cypress. It seems like the problem lies within the TypeScript configuration. Below is a Minimal Working Example (MWE) of my setup. Any ...

JavaScript events are failing to trigger within the content area of an iframe

When attempting to run a given example by double clicking inside the content area of an iframe, the clicks and any JavaScript events are not being fired. Currently, the events can only be triggered by clicking on the border of the iframe, not inside the ...