[Vuejs]-How to use array.find comparing it with another object

0πŸ‘

It works perfectly fine 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 suspect your problem might have something to do with this context. Try an arrow function instead, designs.forEach(design => ... )

0πŸ‘

Just remove this from this.designs and this.articles. Then remove .bind(this) as you dont need to bind them with this.
Here is a working jsfiddle.
But if you are doing it in vuejs then just change 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
})

As scope of this is the inner function in you code. Just replaced that will arrow function. Or you can try with setting value of this outside like let self = this as said in other answers

0πŸ‘

You can also try something like below

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

The issue is with the scope of this. Inside your forEach this.articles does not exists. Hence the undefined error.

Leave a comment