How can we efficiently determine if any of the keys in an array of objects contains a value that is present in another array of arrays object?

I am working on developing a filtering system that checks for the existence of project technologies in the arrOfObjs.name. If a match is found, then the filter will allow the project to be displayed in the DOM. This filter specifically involves using a computed value in VueJS.

For example:

arrOfObjs = [{name: 'test1', image: 'testing1'}, {name: 'test2', image:'testing2'}]
projects: 
[
      {
        name: "testproject",
        description: "lorem ipsum",
        technologies: ["test2", "test7", "test3"]
      },
      {
        name: "atest",
        description: "lorem ipsum",
        technologies: ["test1", "test2", "test5"]
      },
]

This is my current approach:

computed: {
  myComputedVal () {
    projs = []
    this.projects.forEach(p => {
      p.technologies.forEach(t => {
        this.arrOfObjs.filter(o => {
          if (o.name == t) {
            return p // potentially store in array like projs = [...projs, p] and then return projs
          }
        })
      })
    })
  }
}

I aim to determine whether any of the technology values exist within arrOfObjs.name, and if so, either return the matching project or add it to an array for later computation. Currently, no action is being taken based on the existing code.

Answer №1

Here is a code snippet that can be used to filter out projects based on the presence of certain technologies in the array of objects:

By utilizing flatMap(), you can extract all the names into an array as strings first. Then, with the help of filter(), some(), and includes(), you can effectively filter out projects based on the technologies present in the names array like so:

({technologies}) => technologies.some(t => names.includes(t))

If you want to ensure that all elements are present, you can use every() instead:

({technologies}) => technologies.every(t => names.includes(t))

For example, here's how you can implement this using some():

const arrOfObjs = [{name: 'test1', image: 'testing1'}, {name: 'test2', image:'testing2'}],
      projects = [{name: "testproject",description: "lorem ipsum",technologies: ["test2", "test7", "test3"]}, {name: "atest",description: "Lorem ipsum", technologies: ["test1", "test2", "test5"] }];

const names = arrOfObjs.flatMap(e => e.name);
const result = projects.filter(
   ({technologies}) =>
      technologies.some(t => names.includes(t)
      // technologies.every(t => names.includes(t) // if all needed
   )
);

console.log(result);

I hope this explanation is helpful!

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

Troubleshooting the issue of AngularJs location.path not successfully transferring parameters

My page has a Login section. Login.html <ion-view view-title="Login" name="login-view"> <ion-content class="padding"> <div class="list list-inset"> <label class="item item-input"> <input type="te ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Fixing Bugs in Checkbox Functionality using useState in Reactjs when implementing Material UI

I am working on a numeric select functionality where selecting a number renders the component multiple times. Inside the component, there are checkboxes that should not all activate at once when one is selected. https://i.sstatic.net/Q5Csn.png You can vi ...

What is the secret to the lightning speed at which this tag is being appended to the DOM?

Have a look at this concise sandbox that mirrors the code provided below: import React, { useState, useEffect } from "react"; import "./styles.css"; export default function App() { let [tag, setTag] = useState(null); function chan ...

PHP: When an Array Key is Not Defined

https://i.sstatic.net/k2d1Z.png This is the result I am trying to organize and display my data in tables based on the date. I have stored the data from the database in an array for this purpose. However, I am encountering an error warning stating 'un ...

``Symmetric matrix exhibits poor diagonalization due to its ill-conditioned nature. While the eigenvalues are satisfactory, the

I am facing a challenge of diagonalizing an ill-conditioned sparse matrix with very small values. I have successfully achieved this using C++ with LAPACK and now I am hoping to replicate the same in Julia. However, there is a discrepancy in the results obt ...

Embarking on the journey of transitioning code from server-side to client-side

Currently, I am looking to transition the code behind section of my asp.net web forms application to client-side ajax or javascript - still deciding on which route to take. The main goal for this change is to ensure that the application remains functional ...

encountering difficulties compiling production assets using npm run production

npm run production is causing issues for me. I have attempted to delete the node_modules folder and then run npm install, but the problem persists. I also tried uninstalling and reinstalling npm on my system, yet I am still encountering the same error. I ...

Want to achieve success with your AJAX calls in JavaScript? Consider using $.get

As I clean up my JavaScript code, I am looking to switch from using $.ajax to $.get with a success function. function getresults(){ var reqid = getUrlVars()["id"]; console.log(reqid); $.ajax({ type: "POST", url: "/api/ser/id/", ...

The execution of consecutive Ajax requests encounters issues in the Google Chrome and Safari browsers

I am facing an issue where I encounter a problem displaying a sequence of dialogue or AJAX results that depend on each other. For instance, when a user clicks to send a message, it triggers an ajax call, which opens a dialogue box. The user fills out the f ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

What is the best way to assign a unique name to a dynamically generated text box using jQuery

In an effort to name a dynamically created textbox based on a specific event, I attempted the following code. The function GenerateTextBox was intended to assign a name and value of "" to the textbox upon generation, however, the name did not get assigned ...

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

The error encountered with react createRef was caused by a faulty implementation

Here is the revised question post completing the answer In this particular code snippet, I have encountered an issue where my file browser opens correctly upon submission, however, the updated state is not reflected when I click the final submit button. ...

Parsing JSON using C# to extract an array

I have a lengthy JSON with an array embedded within it. The structure of the JSON is not constant and is always changing dynamically. The only thing I am certain of is that the JSON contains this specific array: {"employees":[ {"firstName":"John", " ...

Construct a structure containing the key/value pairs of cells within an HTML table row using JavaScript

I'm completely new to JavaScript so please be patient with me; I'm not even sure if I'm searching for the solution correctly. Despite spending hours googling and experimenting, I still can't get it to work. My issue is related to an HT ...

Error: The variable $traceurRuntime has not been defined in the AngularJS application

Currently, I am utilizing [gulp-traceur][1] to convert es6 to js within my angularjs application (version 1.x). However, when attempting to compile a for loop, an error occurs: ReferenceError: $traceurRuntime is not defined It appears that I may need to ...

Upon completion of an Ajax call, ReactJS will execute a callback function

I'm relatively new to React and encountering an issue. I am fetching data from an API that requires a callback function as a parameter (&callback=cb). I've chosen to use the fetchJsonp library for making cross-domain fetch requests. Despite pass ...

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...

The issue arises when creating a button source code on Gatsby and Stripe, resulting in an error message: "Uncaught TypeError: Cannot read property 'configure' of undefined."

I've been working on developing an e-commerce platform following a tutorial I found here. However, when I check the source code for checkout.js, it throws these errors and the entire page becomes blank. Uncaught TypeError: Cannot read property &apos ...