Guide on utilizing map function in JavaScript and Vue to generate a fresh array

I am working on implementing a map method in JavaScript and Vue to generate a new array of objects while only including specific items in each object. I have designed a user interface with 2 checkboxes corresponding to 2 distinct objects:

    <div v-for="object in objects" :key="object.id" class="max-w-sm rounded overflow-hidden shadow-lg justify-center">
      <div class="px-6 py-4">
        <div class="font-bold text-xl mb-2">{{ object.name }}</div>
      </div>
      <span class="flex-1 flex mt-8 m-2">
        <span class="flex flex-col">
          <input v-model="checkBoxArray" :value="object.id" @click="selectObject(object.id)" type="checkbox" class="h-5 w-5" />
        </span>
      </span>
    </div>
  const objects = [
  {
    id: 1,
    name: 'bucky barnes',
    title: 'winter soldier',
    cellnum: '123-456-7890',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f4d4e5d414a5c6f47564b5d4e014c4042">[email protected]</a>',
    description: 'Description 1'
  },
  {
    id: 2,
    name: 'sam wilson',
    title: 'falcon',
    cellnum: '098-765-4321',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91f7f0fdf2feffd1f0e7f4fff6f4e3e2bff2fefc">[email protected]</a>',
    description: 'Description 2'
  },
]

The selectObject function triggered by the checkbox input adds the id of a selected object to checkBoxArray:

const checkBoxArray = ref([])

const selectObject = (id) => {
  checkBoxArray.value.push(id)
}

A watch property monitors changes to checkBoxArray.value, then invokes a function that uses map to create a new array targeting the id of the selected object:

watch(checkBoxArray.value, () => {
  const storedObjects = objects.map(val => checkBoxArray.value.find(obj => obj === val.id), ['id', 'name', 'title'])
  console.log(storedObjects)
})

My goal is to produce a new array containing an object with ONLY the id, name, and title from the original object. For example:

{id: 1, name: 'bucky barnes', title: 'winter soldier'}

Currently, I am only getting a new array with the id of the selected object. How can I adjust the map and find methods within the watch property to generate a new array with an object containing ONLY id, name, and title?

Here is the complete code snippet:

<template>
  <div>
    <div v-for="object in objects" :key="object.id" class="max-w-sm rounded overflow-hidden shadow-lg justify-center">
      <div class="px-6 py-4">
        <div class="font-bold text-xl mb-2">{{ object.name }}</div>
      </div>
      <span class="flex-1 flex mt-8 m-2">
        <span class="flex flex-col">
          <input v-model="checkBoxArray" :value="object.id" @click="selectObject(object.id)" type="checkbox" class="h-5 w-5" />
        </span>
      </span>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';

  const objects = [
  {
    id: 1,
    name: 'bucky barnes',
    title: 'winter soldier',
    cellnum: '123-456-7890',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="593b382b373c2a1931203d2b38773a3634">[email protected]</a>',
    description: 'Description 1'
  },
  {
    id: 2,
    name: 'sam wilson',
    title: 'falcon',
    cellnum: '098-765-4321',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdaddd0dfd3d2fcddcad9d2dbd9cecf92dfd3d1">[email protected]</a>',
    description: 'Description 2'
  },
]

const checkBoxArray = ref([])

const selectObject = (id) => {
  checkBoxArray.value.push(id)
}

watch(checkBoxArray.value, () => {
  const storedObjects = objects.map(val => checkBoxArray.value.find(obj => obj === val.id), ['id', 'name', 'title'])
  console.log(storedObjects)
})

onMounted(() => {
  console.log(objects)
})
</script>

Answer №1

When it comes to the map function, there is no syntax that filters the fields by a 2nd argument:

                                                             // This parameter will not work
                                                                          👇
objects.map(val => checkBoxArray.value.find(obj => obj === val.id), ['id', 'name', 'title'])

The correct approach is to filter the objects that are stored first, and then apply map to transform them:

const storedObjects = objects
.filter(obj => checkBoxArray.value.find(id => id === obj.id)) // this returns the array of object that are stored
.map(elm => {
 return {
   id: elm.id,
   title: elm.title,
   name: elm.name
 }
})

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 CSV into an Array of Hash Tables

Currently, I am working on parsing a CSV file and creating an array of hashes. While I initially implemented this using my own code, I feel that it may not be the most efficient solution. My aim is to utilize the CSV-Parser library, but so far, I have only ...

Styling of checkboxes in jQuery Mobile is missing after an AJAX request

I am currently working on implementing an ajax call to retrieve a list of items from a json array and display them as checkboxes. While the items are loading correctly, they lack the jquery mobile styling. $(document).ready(function(){ ...

Iterating through images one time and capturing the mouse coordinates for every click made by the user

I have the following code snippet that displays a series of images and I would like to capture the coordinates of each mouse click on these images. Is there a way to send these coordinates to my email at the end of the image loop? Any assistance in achievi ...

tips on displaying textbox content on a php webpage

I have a piece of code where, when text is entered into a textbox and the add attribute button is clicked, the entered value is displayed on the page twice. One appears in the first row of a table, and the other appears in the first row of a second table. ...

Tips for combining two arrays by property value in React using ES6

I am facing a challenge with two arrays: array1 = [{"sourceId": "1", "targetId": "2", "name": "heats air"} , {"sourceId": "3", "targetId": "4", "name": "power"}] array2 = [{"name": "Hair Dryer", "id": "1"}, {"name": "Heating System", "id" ...

Setting multiple cookies with the setHeader method in NodeJs is a powerful capability that allows developers

Currently working on a project using node js, and I've encountered an issue with setting two different cookies. Every time I try to set them, the second cookie ends up overwriting the first one. Check out the code snippet below that I'm currently ...

How to manage rejections in async/await within the Array#map method

In my Node 8.1.2 project, I encountered a scenario where one file is calling another file's function within a map structure. While in a real example, I would normally use Promise.all on the map, that specific implementation is not the focus of this qu ...

Enhance the HTML content using a JavaScript function

Here is the code that I have: <label>Brand</label></br> <select name="brand" id="brand" onChange="changecat(this.value);"> <option value="" selected>Select Brand</option> <option value="A">AMD</option&g ...

Loading images in advance with AJAX for enhanced AJAX performance

My website is structured in a sequential manner, where page1.html leads to page2.html and so on. I am looking to preload some images from the third page onto the second page. After searching, I came across this amazing code snippet: $.ajax({ url ...

What is the best way to link a search field and a datatable in separate views using VUEJS?

I have added a search field in the navbar section of my application and I'm looking to link it with the datatables located in another file. Should I use pops or events for this connection, and what would be the appropriate code structure? This is ho ...

What is the best way to successfully send an object through AJAX once all its updates are completed?

I am experiencing an issue with my JavaScript code within an event: var userData = tableWidget.grid('userData'); console.log(tableWidget.grid('userData')); $.ajax({ "url": "../../server/query.aspx?tableEvent=reordercolumns&tabl ...

Encountering: Unable to break down the property 'DynamicServerError' of 'serverHooks' as it does not have a defined value

An error has arisen in a Nextjs app with TypeScript, specifically in the line of my react component which can be found here. This is my inaugural package creation and after several trials, I managed to test it successfully in a similar vite and TypeScript ...

What is the best way to define properties for objects within views.py so that the updated object can be effectively passed to JavaScript code?

When loading an "endless scroll" feed via AJAX and pagination, I realized that before passing objects to the JS code, I need to add a property (or attribute) to every object indicating whether it was liked by the current user or not. However, my initial ...

React Router version 6.4.5, automatic redirection upon loading the page

Seeking assistance with setting up redirects. Below are snippets of the code. index.js const router = createBrowserRouter([ { //Defining App as the root element... path: "/", loader: () => { }, element: <App/>, ...

What could be the reason why Spring Boot is unable to access the front-end static resources located in the "dist" folder?

After importing the files packaged by the front-end developer into the dist project and running SpringBootApplication, I encountered an issue. Although I can access the index.html page, I am unable to view its static resources - resulting in a blank screen ...

If an element with a "hidden" display property is loaded in the browser window, will it be visible?

Is an element in a hidden display still using memory when the page is loaded? It's convenient to have many elements on a page, but if 99 elements are hidden and only 1 is displayed, does that impact the loading of the page? I'm curious if the pa ...

Countdown malfunction: wrong date displayed

Utilizing the Countdownjs library in my project is resulting in an incorrect day count. Incorporating AngularJS, here is the custom directive I've implemented for the countdown: .directive('tempoPercorrido', function($interval){ ret ...

Tips for refreshing CSS following an ajax request

Currently, I am facing an issue with the CSS formatting on my page. I am using Django endless pagination to load content on page scroll. However, when new content is loaded, the CSS applied to the page does not work properly and needs to be refreshed. Can ...

When using Firestore in Android, I encounter a nodejs error regarding headers being sent prematurely

Currently, I am utilizing a webview in order to display content from a nodejs server. While requesting a page works as expected, accessing firestore results in an error where it seems like nodejs is attempting to resend the page. Below is the code for an a ...

Hiding the initial parent SVG element in the list will also hide all subsequent SVG elements within each section, excluding the container

I encountered a strange issue with my code in the Next framework. When using getServerSideProps, I made a request to my api folder, which resulted in a simple JSON response. Everything seemed to be working fine. The content was displayed perfectly without ...