Filter an object by an array and display it based on this array using Viewjs

Trying to filter an object from an array using another array in a JSON feed that has one array with objects and object within objects:

members = [
    {
        id: 1,
        name: "Ruta"
    },
    {
        id: 2,
        name: "Paul"
    },
    {
        id: 3,
        name: "Raymond"
    }
]

roles = {
    0: {
        id:  1,
        title: "admin",    
        member: [1,2],
        status: 
    },
    1: {
        id:  2,
        title: "editor",    
        member: [1]
    },
    2: {
        id:  3,
        title: "moderator",    
        member: [3]
    }
}

The attempted approach to get roles by member is not working as intended

members() {
    return Object.values(members).filter((el) => { 
        return this.roles.map((id) => { return id }).includes(el) 
    })
},

Displayed in Vue

<div v-for="(member) in members">
    <div>
        {{member.name}}
    </div>
    <div v-for="(role) in roles">
        {{role.title}}
    </div>
</div>

Desired result:

Result: 

    Ruta
       - admin
       - editor
    Paul
       - admin
    Raymond
       - moderator

Answer №1

Initially, if members is an array, utilizing Object.values(members) may result in triggering an error.

Furthermore, I believe the correct approach involves iterating over members first and then appending the filtered roles to each member as opposed to the current logic.

  members() {
    return members.map(member => {
        return {
          ...member,
          roles: Object.values(roles).filter(role => role.member.includes(member.id))
        }; 
    });
},

Answer №2

const teamMembers = [{
    id: 1,
    name: "Elena"
  },
  {
    id: 2,
    name: "David"
  },
  {
    id: 3,
    name: "Sophia"
  }
];

const roles = [{
    id: 1,
    title: "manager",
    member: [1, 2],
    status: 1
  },
  {
    id: 2,
    title: "assistant",
    member: [1]
  },
  {
    id: 3,
    title: "coordinator",
    member: [3]
  }
];

const outputData = teamMembers.map(member => ({
  name: member.name,
  role: roles.filter(role => role.member.includes(member.id)).map(m=>m.title)
}));

console.log(JSON.parse(JSON.stringify(outputData)));

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

Tips for retrieving the value of a table cell when the checkbox in the corresponding row is selected

Within my project, I am utilizing a table. The html code I am using is as follows: <table id="assTB" border="1px" cellspacing="0"> <colgroup> <col style="width:15%"> <col style="width:15%"> <col sty ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

Leveraging conditional statements for dynamically computed Vue properties

In the Vue site I'm working on, there is a functional button that changes its state when clicked (from "pause" to "resume" and also changes colors). The button functionality itself works perfectly, but I am facing an issue in aligning it with another ...

Experiencing a java.lang.OutOfMemoryError while attempting to convert a large PDF file into a byte array

My attempt to read a large pdf file using byte Array isn't going as planned. Here is the code I am using: String RESULT "D/new/certficateVisualFinal.pdf"; try { FileInputStream fileInputStream=null; File file = new File(RESULT); ...

Steps for implementing virtual scroll to render items in a CDK table

Utilizing CDK VIRTUAL SCROLL within a table to load data from an API service, I encountered an issue where removing all columns and then requesting them back only brings the columns back but not their respective items. Is there a solution for this proble ...

Navigating through File URLs to access desired folders or directories

I have a group of users connected to an internal network, each with a mapped drive to a server (E:). All users are running Windows 7 and use Firefox as their browser. To allow access to MySQL files using PHP, I have set up XAMPP on the server. Currently, ...

Efficient database optimization for handling numerous ajax/php requests in PostgreSQL

I'm currently using AJAX and PHP for updating a postgreSQL database. Imagine having 1000 users sending one ajax post request per second to a php script. This would mean that the php script opens a connection, runs two SQL update commands each time, a ...

When working with JObject return type, an empty Array will be returned in JSON

When sending a request from Postman which hits the API in the backend, the return type of the method is JObject. I am using JObject.Parse method to parse the string but getting an empty array as a result. Update to Newtonsoft (to version 10) has occurred. ...

Validating forms on the server while using client-side forms in Angular Material

A basic form collects the name and price of a menu item and stores it in a database. A server route is set up to check if the item already exists in the menu. If it does, an error message is sent back through res.json() like this: if (newItem) { //Add ...

Is the ajaxToolkit PopupControlExtender malfunctioning? Could it be due to being outdated?

I recently tried following a tutorial on using ASP.NET Ajax Popup Control to display GridView row details. However, I encountered a runtime error when attempting to perform a mouseover action. The error message reads: Sys.ArgumentUndefinedException: Va ...

PHP - Retrieve distinct values from a multidimensional array

Within my array are the following elements: Array ( [0] => Events - Central [1] => Central [2] => Finance [3] => 17 [5] => 11 [8] => 11 ) Array ( [0] => Events - Central [1] => Central [2] => HR [3] => 17 [5] => 11 [8] =&g ...

How can I pass props from a custom _app.js file to the <Navbar> component in Next.js?

How do I go about passing props to a Navbar component that will be included under the Head component? Although I successfully passed props in the index.js page using getServerSideProps, it seems to not work properly in the _app.js file. import ".. ...

Can we begin processing the array from the second element onwards?

Currently working with a PHP array and interested in utilizing the foreach function to iterate through entries, skipping the first one ([0]) and starting from [1], [2], and so on. Appreciate any help with this. Thank you! ...

Generating SCSS variables dynamically in Vue.js can add a powerful level of customization and flexibility

Within my App.vue @mounted() method, I initiate an api request to acquire data for my application. Embedded in a response property called "style", the json object containing various styling information appears as follows: "style": { &qu ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

Can AngularJS support HTML5-mode URL routing in locally stored files (using the file:// protocol)?

Sorry if this question has already been asked, but I haven't been able to find any information on it. I'm working on an AngularJS application that needs to be accessed directly from a hard drive (not through a traditional HTTP server), so the UR ...

"Utilize AJAX to submit the value of the text box input from a jQuery slider when the Submit Button

Whenever I adjust the sliders, the value is shown in an input textbox. However, when I move the slider and check the values echoed from the textboxes on another PHP page, they are always displaying as 0. Even after clicking the submit button, it still echo ...

Identify a request in NodeJS without relying on express or accessing the request object independently of an express middleware

I am struggling with accessing the request object outside of an express middleware in NodeJS. In my code snippet below, I need to read the request object from a file called mongoose_models.js, where I don't have access to the express middleware argume ...

It appears that JavaScript has the capability to automatically remove event listeners from textareas

Greetings to all members of the community, I have developed a web application (see code below) that, when double-clicked, inserts a text area into the frame. Upon double-clicking the text area, it changes its color to green, and with another double-click ...

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...