Filtering an array of JSONs in Vue.js using a separate array of JSONs

In my code, there are two arrays of JSONs: one named products and another called deletedProducts.

The task is to filter out the products that are not present in the deletedProducts array.

For instance:

products = [
  {
    id: 1,
    name: 'Box'
  },
  {
    id: 2,
    name: 'Lamp'
  }
]
deletedProducts = [
  {
    id: 1,
    name: 'Box'
  }
]

The filtered result would look like this:

result = [
  {
    id: 2,
    name: 'Lamp'
  }
]

Answer №1

Here is a solution using the filter and find methods:

let result = products.filter(prod => {
    return !deletedProducts.find(dprod => {
        return dprod.id === prod.id;
    })
})

let products = [{
    id: 1,
    name: 'Table'
  },
  {
    id: 2,
    name: 'Chair'
  }
]

let deletedProducts = [{
  id: 1,
  name: 'Table'
}]

let result = products.filter(prod => {
  return !deletedProducts.find(dprod => {
    return dprod.id === prod.id;
  })

})

console.log(result)

Answer №2

Check out this comparison function and filtering method. (referencing an array based on element "id" in this example)

 let items = [
  {
    id: 1,
    name: 'Chair'
  },
  {
    id: 2,
    name: 'Table'
  }
]

let removedItems = [
  {
    id: 1,
    name: 'Chair'
  }
]

function compareArrays(secondaryArray){
      return function (current) {
          return secondaryArray.filter(function(item) {
              return item.id === current.id
          }).length===0;
        }
    }


var results=items.filter(compareArrays(removedItems));

console.log(results);

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

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

Unable to determine the reason why the JavaScript plugin is not functioning as expected

I have been attempting to set up a JS modal window and have essentially copied the code for the plugin exactly as instructed, but it is not functioning properly. Here is my code... <!doctype html> <html> <head> <meta charset="utf- ...

Incomplete data retrieval issue encountered during .ajax call

I am having trouble retrieving all 4 key|value pairs from a page that displays an object as text in the body and pre tag. It seems to be missing one pair - any ideas why? Just a heads up, I've tweaked some of the URLs and data in the JSON output for ...

Using a semicolon at the end of the line is considered a favorable practice when writing ES6 code in Babel

After browsing through various tutorials on the internet that utilize redux and react, I came across a common trend of omitting semicolons in ES6 code when using Babel. For instance, some examples neglect to include semicolons at the end of import or expo ...

What are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

Performance comparison between Javascript Object and Map/Set for key lookup

I decided to experiment with the performance of JavaScript Object, Map, and Set when it comes to accessing keys. I tested the following three code snippets on JSBEN.CH. Objects const object = {}; for (let i = 0; i < 10000; ++i) { object[`key_${i}` ...

What is the best way to trigger the keyup event in that moment?

Currently, I am using regex to validate the name field. Each time a key is pressed, a validation function is triggered. If the input matches the regex pattern, I need to empty out that specific character from the input field. However, when previewing the p ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Getting information from a MySQL database and transferring it to an Android device

I'm attempting to retrieve user details from MySQL to my Android application. I am posting data from Android and obtaining the values using $_POST['mobile'] and $_POST['usertype'] in my PHP page. To verify if the data is being post ...

"Enhance your user experience with an expandable listview that displays a variety of data within each

I am trying to show group and child data in my app. I found a tutorial on JournalDev that demonstrates how to use an ExpandableListView, but it only shows a single item for each parent and child view. I need help setting multiple items for both parents and ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Is there a way to detect and handle errors triggered by a callback function?

My component has the following code snippet: this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); }); Additionally, my service contains this method: login(credentials, callback) { co ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

What is the best way to incorporate the PUT method...?

Within the realm of programming, there exist three distinct files with specific roles - profiles.model.js, profiles.controller.js, and profiles.router.js. The focus now shifts towards implementing the PUT method across these three files. To begin, profiles ...

Building queries on the client side with Django

For my AJAX-driven web page that relies on JSON responses from API queries, I am facing the issue of constantly needing to update the API interface whenever new functionalities are required. These updates typically involve crafting database queries and con ...

Product sketching libraries in JavaScript

Can somebody assist me in locating a suitable JS library that is capable of generating a product sketch similar to this one: Partition sketch? I am currently using Next.js, and I am encountering difficulties with most libraries due to Next.js utilizing SSR ...

In React, I'm unable to navigate to a different page

My English may not be the best, but I am working on creating a Login Page. The issue I'm facing is that when I click the Login button, I want to navigate to the Home Page I designed using React. However, whenever I try to implement Link or Route comma ...

Colorful radial spinner bar

I am interested in replicating the effect seen in this video: My goal is to create a spinner with text in the center that changes color, and when the color bar reaches 100%, trigger a specific event. I believe using a plugin would make this task simpler, ...

Preventing Shift: How to Only Replace the Chosen Vue Draggable Item Without Affecting Other Grid Items

Let's try an example to demonstrate: https://codesandbox.io/s/j4vn761455?file=/src/App.vue:112-116 Step 1: Drag item 4 to where 5 is. Notice how 4 and 5 switch positions. Step 2: Now, drag item 1 to position 6. Watch as 1 moves to where 6 was, pushi ...

Discovering the process of retrieving API data upon a button click within Next.js using server-side rendering

Hi there, I'm fairly new to working with next.js and would greatly appreciate some assistance. I am trying to figure out how to fetch data from an API upon clicking a button in next.js on the server side. I understand that using onClick directly is ...