Exploring ways to utilize array.find by comparing it to a different object

There are two arrays in JavaScript named designs and articles.

var designs = [
    {
        design_id:"bwbmbqlujurv", article_id:14782, name:"adidas demogorgon black"

    }, 
    {
        design_id:"lg9yba2gkcwr", article_id:14782, name:"harry potter wand"

    }, 
    {
        design_id:"ztvx3yikkkyx", article_id:5570, name:"hogwarts map"
    }, 
    {
        design_id:"hlzd4afi9en5", article_id:5570, name:"lannister lion"
    }, 
    {
        design_id:"sdwererefwff", article_id:14782, name:"pokemon bulbasaur"
    },
];

var articles = [
    {
        article_id:6508, dsn_shared_art_id:null, name:"tee man two sides"
    },
    {
        article_id:13510, dsn_shared_art_id:null, name:"tee woman two sides"
    },
    {
        article_id:5570, dsn_shared_art_id:null, name:"necktie"
    },
    {
        article_id:14782, dsn_shared_art_id:null, name:"sweetwear with hood"
    },
]

I am trying to access the value of the first element in the array articles that meets the following conditions:

article => article.article_id == design.article_id || article.dsn_shared_art_id == design.article_id

The .find method is not working as expected:

this.designs.forEach(function(design) {
    var $artdata = this.articles.find(article => article.article_id == design.article_id || article.dsn_shared_art_id == design.article_id);
    console.log($artdata);//undefined
}.bind(this));

How can I correct this issue?

Answer №1

Everything is running smoothly for me:

var designs = [
    {
        design_id:"bwbmbqlujurv", article_id:14782, name:"adidas demogorgon black"

    }, 
    {
        design_id:"lg9yba2gkcwr", article_id:14782, name:"harry potter wand"

    }, 
    {
        design_id:"ztvx3yikkkyx", article_id:5570, name:"hogwarts map"
    }, 
    {
        design_id:"hlzd4afi9en5", article_id:5570, name:"lannister lion"
    }, 
    {
        design_id:"sdwererefwff", article_id:14782, name:"pokemon bulbasaur"
    },
];

var articles = [
    {
        article_id:6508, dsn_shared_art_id:null, name:"tee man two sides"
    },
    {
        article_id:13510, dsn_shared_art_id:null, name:"tee woman two sides"
    },
    {
        article_id:5570, dsn_shared_art_id:null, name:"necktie"
    },
    {
        article_id:14782, dsn_shared_art_id:null, name:"sweetwear with hood"
    },
]


designs.forEach(function(design) {
var $artdata = articles.find(article => article.article_id == design.article_id || article.dsn_shared_art_id == design.article_id);
console.log($artdata);//undefined
}.bind(this));

I have a feeling that your issue could be related to the this context. Give an arrow function a try instead,

designs.forEach(design => ... )

Answer №2

Consider exploring a different approach like the example provided below:

let current = this;
current.designs.forEach(function(design) {
    let artdata = current.articles.find(article => article.article_id == design.article_id || article.dsn_shared_art_id == design.article_id);
    console.log(artdata);
});

The issue at hand revolves around the scope of this. Within the forEach function, this.articles is not accessible hence leading to an undefined error.

Answer №3

To simplify your code, remove this from this.designs and this.articles. Also, eliminate .bind(this) as it is unnecessary to bind them with this. Click here to see a working jsfiddle. However, if you are working in vuejs, update your forEach method like this:

this.designs.forEach((design) => {
  var $artdata = this.articles.find(article => article.article_id == design.article_id || article.dsn_shared_art_id == design.article_id);
  console.log($artdata);//undefined
})

Since the scope of this is the inner function in your code, replace that with an arrow function. Alternatively, you can set the value of this outside using let self = this, as suggested in other answers.

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

Setting the initial date value for an Angular Material md-datepicker to a specific date

When using Angular Material md-datepicker, by default the system's current date is set as today's date and highlighted in the calendar. However, I am looking for a way to manually set any given date as today's date instead. Please see this i ...

Unable to link myxins with Quasar on a worldwide scale

Encountered an issue with an 'Undefined mixin' error while attempting to utilize a mixin in a Quasar project within a Docker container view image description here comments displayed on the screen here is the specific mixin included it in both t ...

The hover functionality fails to activate when a z-index is applied

My issue revolves around 2 divs: one containing a link and the other a box-shaped container. The link is set with position:fixed; causing it to fly over the container div. To resolve this, I attempted to assign a negative z-index value to the link, but unf ...

How can I determine the size of the custom options dropdown in Magento?

I'm facing a challenging issue that I can't seem to crack. It might be because I'm still learning the ropes and struggling with technical jargon. Please bear with me as I try to explain my problem. Here is a summary of what I'm trying ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

What role does @next/react-dev-overlay serve in development processes?

Currently, I am diving into a NextJs project. Within the next.config.js file, there is this code snippet: const withTM = require('next-transpile-modules')([ 'some package', 'some package', 'emittery', ...

Utilize CSS styling on dynamically loaded HTML content

I am working on a project similar to the StackOverflow editor. I am fetching markdown text, converting it to HTML, and then displaying it in a preview area. However, when I try to style the injected HTML elements using CSS, the styles are being ignored. Up ...

Can you explain the functions of this "malicious" JavaScript code?

I came across this piece of code on a website that labeled it as "malicious" javascript. Given my limited knowledge of javascript and the potential risks involved in trying out the code on my own site, I was hoping someone here might be able to shed some l ...

Click on any checkbox to select all checkboxes at once

I have created a table with each column containing a checkbox. My goal is to select all checkboxes in the table when I click on the checkbox in the top row (th). Can someone guide me on how to achieve this? Below is my code: <table style="width:100%"& ...

Providing secure access to Apostrophe-CMS S3 assets and attachments via HTTPS

Currently, I am utilizing Amazon S3 to deliver both my static assets and user uploads within the context of apostrophe-cms. While my site is loading via https, all of my assets appear to be loading using http. I have set up a cloudfront distribution at th ...

Unable to assign an IP address to an Express JS application

Struggling to test a specific endpoint in Express, but consistently encountering a 404 error. var express = require("express") var app = express() //var http = require('http').Server(app) app.get('/', function(req,res){ res. ...

Updating View in Angular 2 ngClass Issue

I'm encountering some challenges with updating my view using ngClass despite the back end updating correctly. Below is my controller: @Component({ selector: 'show-hide-table', template: ' <table> <thead> ...

Highlight a pair of words in a phrase using jquery technology

Only one word in my code is highlighted $(document).ready(function() { let firstword = 'web'; let secondword = 'js'; $(".field.ConditionsAccept>.caption:contains('" + secondword + "'):contains('" + firstword ...

An unexpected 'undefined' value is being added to a particular Web API request

I am encountering an issue in my Angular application where the word 'Undefined' is being appended to a specific WebAPI call, causing both registerUser and login requests to fail. Here are the problematic request URLs: Request URL: http://localho ...

Utilizing a series of linked jQuery functions

Is there a more efficient way to write this code snippet? $('#element').html( $('#element').data('test') ); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="el ...

Combining vueJS and webpack to bring in fonts, CSS styles, and node_modules into your project

I've recently started working with Vue.js and Webpack, and I'm facing some challenges regarding the correct way to import and reference fonts, CSS, and node_modules in my project. My project structure looks like this, as set up by vue-cli: buil ...

common mistake: using a while loop inside a foreach loop

I am completely new to php and have been struggling to find a solution on my own. Here is the snippet of code that I've been working with: $i = 0; $j = 0; $lastchange = 0; $pricearray = array(); $onlyprices = array(); foreach ($mymainlist as $key =&g ...

What is the best way to implement a custom toast delay in a React application using setTimeout

The concept is straightforward: When the function showToast is called, I aim to change my toast's className to show, and then remove it by replacing with an empty string after displaying it for 3 seconds. HTML: <div id="toast">New col ...