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

Errors encountered when using Puppeteer on Kubernetes: "Detached navigation frame" and "Attempting to access main frame too soon"

I have been attempting to execute a nodejs based Docker container on a k8s cluster, but I am encountering persistent errors: Navigation frame was detached Requesting main frame too early In an effort to resolve this issue, I have condensed the code to ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

Building a WordPress calculator form that retains user input without requiring a resubmit and incorporates custom field values

Currently tackling a challenge on my Wordpress website. Without any code yet (after numerous attempts at rewriting 4 different forms), I'll simply outline what I aim to accomplish, confident it's a straightforward task with something crucial elud ...

Javascript alert: An issue has been detected when attempting to open a URL along with the user's input through Javascript

Having trouble with my javascript codes... I'm trying to create an input box and submit button. Whatever the user inputs in the box should be added to the default web URL, but it's not functioning as expected. The issue I'm facing is that ...

Ways to exclusively trigger the onclick function of the primary button when dealing with nested buttons in React.js

Let me elaborate on this issue. I have a List component from material-UI, with ListItem set to button=true which makes the entire item act as a button. Within the ListItem, I have added a FontAwesomeIcon. To hide the button, I set its style to visibility: ...

The layout of the keyboard in Cordova has been altered

Just starting out with my first Cordova app and I'm working on a simple login form. The issue I'm facing is that whenever I click on an input element, the keyboard pops up and completely messes up my layout, which should be straightforward. Has ...

Stylish hover effects displayed on disabled button using Styled Components

I am currently working on a button using Styled Components. However, even when the button is in a disabled state (:disabled), it still exhibits hover behavior that should not be present. I am wondering if there is a proper way to prevent hover effects when ...

Tips for resizing a Textbox by dragging in asp.net?

Is there a way to dynamically adjust the size of a Textbox by dragging it in an ASP.NET application during run-time? ...

Solution for adjusting line width on Windows in Three.js

I'm currently working on creating a dynamic 3D coordinate system using the Three.js library. My goal is to add some thickness to the axes, which I've been able to achieve by adjusting the LineBasicMaterial's linewidth parameter. The code sn ...

Using document.getElementById will only target a single item

Essentially, I am facing an issue where the document.getElementById() function only works for the first product when I click on the addToBasket button. It always changes the details of the first product, even if I click on a different one. Is there a way ...

Executing a node.js function within an Angular 2 application

Currently, I am running an Angular2 application on http://localhost:4200/. Within this app, I am attempting to call a function located in a separate node.js application that is running on http://localhost:3000/. This is the function call from my Angular2 ...

Utilizing JavaScript to send various arrays to a .NET web service

Hey everyone, I'm currently facing an issue with posting multiple arrays to a .net web service and here is the signature of the web service. <WebMethod()> _ Public Function Lib_Processor(ByVal w_vendor As String(), _ ...

The Vue router2 is failing to capture routes that are deeply nested within the

Organizing my routes into separate files, I have the following structure: export const router = new VueRouter({ mode: 'hash', base: __dirname, saveScrollPosition: true, history: true, routes : Array.concat(userRoutes, siteRou ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

Issues with grunt - Alert: Task "ngAnnotate:dist" has encountered an error. Proceed using --force option

Encountering an unexpected issue with a Grunt task that previously ran smoothly. The error message is as follows: Running "ngAnnotate:dist" (ngAnnotate) task Generating ".tmp/concat/scripts/scripts.js" from: ".tmp/concat/scripts/scripts.js"...ERROR >& ...

What could be the reason behind the malfunctioning of a custom filter in this specific Vue 3 application?

In my development project, I am creating a Vue 3 CRUD application for managing Users. The goal is to display the users in reverse order so that the newest additions appear at the top. To achieve this, I have implemented a custom filter as shown below: reve ...

Chrome experiences a hidden stalling issue due to a large WebGL texture

While working with WebGL on Windows 10 using Three.js, I noticed that initializing a large (4096 x 4096) texture causes the main thread of Chrome to stall for a significant amount of time. Surprisingly, the profiler doesn't show any activity during th ...

Using CSS height 100% does not function properly when the content overflows

Here's what's going on with this code snippet: HTML <div class="one"> <div class="will-overflow"> </div> </div> CSS html, body { width: 100%; height: 100%; } .one { height: 100%; background: r ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

Console.log() will not display any JSON duplicates

My JSON data structure is pretty flat and can have duplicate attributes. I built a logic to remove the duplicates but when testing it out, something strange happened. The logic was always counting the attributes once, resulting in no duplicates. To test th ...