Examining an Array of Objects Based on Various Attributes

Looking to find a way to check if a similar object already exists in an array of objects. Specifically, I want to know if there is an object with the same make and model properties (Ford Focus):

{
  make: 'Ford',
  model: 'Focus',
  color: 'red',
  year: 2016
}

within this array:

[
  {
    make: 'Ford',
    model: 'Focus',
    color: 'blue',
    year: 2008
  },
  {
    make: 'Ford',
    model: 'Mustang',
    color: 'red',
    year: 2011
  },
  {
    make: 'Chevy',
    model: 'Malibu',
    color: 'blue',
    year: 2012
  },
  {
    make: 'Ford',
    model: 'Focus',
    color: 'black',
    year: 1999
  }
]

I am hoping for an efficient ES6 solution but open to using lodash as well. While lodash’s _.some function seems like it could work, it either matches the whole object or only one property. I am also looking for functionality similar to _.pullAllWith, where I can remove all objects that have specific properties (in this case, delete all objects containing Ford Focuses).

Answer №1

JavaScript provides the useful functions some() and filter()

var cars = [
  {
    make: 'Ford',
    model: 'Focus',
    color: 'blue',
    year: 2008
  }, {
    make: 'Ford',
    model: 'Mustang',
    color: 'red',
    year: 2011
  }, {
    make: 'Chevy',
    model: 'Malibu',
    color: 'blue',
    year: 2012
  }, {
    make: 'Ford',
    model: 'Focus',
    color: 'black',
    year: 1999
  }
];

The some() function checks if any element in the array matches certain properties:

const containsFordFocus = cars.some( car =>  car.make === 'Ford' && car.model === 'Focus');
console.log(containsFordFocus); // true

On the other hand, the filter function can be used to exclude elements from an array based on specific conditions:

const filteredArray = cars.filter( car => car.make !== 'Ford' && car.model !== 'Focus');
console.log(filteredArray); // [ { make: 'Chevy', model: 'Malibu', color: 'blue', year: 2012 } ]

Answer №2

Implement a function utilizing the some and every methods, designed to work with any keys provided.

function checkProperties(arr, obj, ...keys) {
    return arr.some(element => keys.every(key => element[key] && obj[key] && element[key] === obj[key]));
}

console.log(checkProperties(arr, check, 'make', 'model'));
<script>
let arr = [
    {
        make: 'Ford',
        model: 'Focus',
        color: 'blue',
        year: 2008
    },
    {
        make: 'Ford',
        model: 'Mustang',
        color: 'red',
        year: 2011
    },
    {
        make: 'Chevy',
        model: 'Malibu',
        color: 'blue',
        year: 2012
    },
    {
        make: 'Ford',
        model: 'Focus',
        color: 'black',
        year: 1999
    }
]

let check = {
    make: 'Ford',
    model: 'Focus',
    color: 'red',
    year: 2016
};

</script>

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

Adding styles dynamically using methods is not supported in Vue.js

When it comes to adding styles to an HTML element from methods, I ran into a small hiccup. Here's what I tried: <div class="add-profile-img" v-bind:style="getBackgroundImg()"> The method in question is: getBackgroundImg: function() { return { ...

Single jQuery scrolling loader malfunctioning in WebKit browser

I've been conducting an interesting experiment in which new entries are dynamically loaded onto a page as you scroll down. Check out a practical demonstration here. In Firefox, everything seems to be working perfectly. However, when viewed in WebKit ...

Ensuring the accuracy of URLs using JavaScript

I am developing a form with an input field for entering a URL and a submit button. I want to incorporate JavaScript validation to show an alert box when a correct URL is entered. Is it achievable using JavaScript? If so, can you please guide me on how to i ...

Tips on saving a form submit button data to localStorage

As a newcomer, I am on a quest to make this function properly. My goal is to create a form where the submit button saves data to the localStorage. Here's what I have tried thus far. <script> function storeRecipe() { localStorage.setItem($(" ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...

Updating JSON data post XMLHttpRequest call

Currently experiencing a puzzling moment. I'm attempting to insert more information into my object after retrieving it from an external source (just for testing purposes, I intend to add random values). Without further ado: As an example, here is w ...

Tips for extracting both the div and entire inner content using JavaScript

I need to retrieve the inner content of a div using JavaScript For example: <div id="content" style="height: 20px; overflow: hidden"> content<br>content<br>content<br> </div> This is my HTML code. I only know the div&apos ...

Explaining how to iterate through objects (one by one) in the This.questionnaire.Profile at every click using JavaScript (answer not found in forums)

Creating a series of questions, each part being stored in This.question = {p1: {...}, p2: {...}, p3: {...}, p4: {...}, p5: {...} etc. (and many more). I want to be able to switch from one article to the next every time I click a button... click => next ...

Pulling JSON Data with Ajax Request

I am attempting to retrieve the following JSON Data: {"status":"success","id":8,"title":"Test","content":"This is test 12"} Using this Ajax Request: $.ajax({ url: 'http://www.XXX.de/?apikey=XXX&search=test', type: "GET", dataType: 'js ...

Sharing specific information with a particular component instance in React using .map

I have set up multiple instances of a child component within a parent component using the following code: render() { return ( {this.state.accounts.map(account => <EachAccount key={account.id} curAccountData={account} /> ...

JavaScript code to make titles slide in as the user scrolls

Looking for a better way to make all titles slide in upon scrolling instead of coding individually? Consider using a forEach loop! Here's how you can modify the code below: function slideInLeft() { document.querySelectorAll('.subtitle-left ...

Ember.js encountering an "Access-Control-Allow-Origin" error with Ajax

Seeking opinions on how to resolve the Access-Control-Allow-Origin issue in this simple Ajax code snippet. Attempts to define the Ember "Access-Control-Allow-Origin": "* " have been unsuccessful. Has anyone with a similar problem found a solution? The URL ...

Navigate through JSON data to extract URLs

As a newcomer to Python, I find myself struggling with parsing JSON data to extract URL values using a Python function. In the given JSON example, my goal is to retrieve URLs nested under the Jobs tag and categorize them into two arrays based on whether th ...

Deciphering the JavaScript code excerpt

This information was sourced from (function ($, undefined) { // more code ... $.getJSON("https://api.github.com/orgs/twitter/members?callback=?", function (result) { var members = result.data; $(function () { $("#num- ...

Struggling to retrieve JSON data from MYSQL database to Android App? Reach out for assistance with

I'm currently working on an Android application that interacts with a remote MYSQL database to retrieve information using JSON data. One of the challenges I'm facing is implementing a search functionality based on the userID in the app, and then ...

Error: The specified module 'sqlite' does not have an export named 'default' as requested

Having some difficulty with importing sqlite into my project. When I add this line: import sqlite from 'sqlite'; An error occurs: file:///D:/WebPro/WebProg/cwCode/dbInteract.js:2 import sqlite from 'sqlite'; ^^^^^^ SyntaxError: ...

Troubleshooting a CORS problem with connecting an Angular application to a Node server that is accessing the Spotify

I am currently working on setting up an authentication flow using the Spotify API. In this setup, my Angular application is making calls to my Node server which is running on localhost:3000. export class SpotifyService { private apiRoot = 'http://lo ...

Is there a way to include a variable in the URL for an AJAX call?

When working with a PHP function that requires an ID and adding a variable to the Ajax URL, the following code snippet can be helpful: PHP Code: function get_json_selected($purpose) { $ids = explode(",", $this->input->post("ids")); ...

Obtain elements from a nested array in JSON format

While working on HTML elements within the "Test" object, I am creating individual elements for each object. These objects can be either type:block or type:list and may contain an array named "List" when they are of type:list. I aim to generate an HTML ".p ...