Exploring the advanced search capabilities of the _.where method in the underscore.js library

var x = {
    "name": "Example 1",
    "status": {
        "id": 1
    }
}

var y = {
    "name": "Example 2",
    "status": {
        "id": 2
    }
}


var z = [x, y];

var w = _.where(z, {
    "name": "Example 2",
    "status": {
        "id": 2
    }
});
//w => returns an empty array []

In this scenario, the expectation was to obtain a reference to the object in memory with w, however, it actually operates only on root properties.

_.where(z, {name: "Example 2"});
=> returns [object]

where object represents the reference for z[1];

EDIT: discovered a possible solution using _.filter()

_.filter( z, function(entry){ 
    if (entry.name == "Example 1" && entry.status.id == 1){
        return entry;
    } 
})

returns => [object] with reference for variable x

Answer №1

If you're wondering how to filter objects based on specific key/value pairs, _.filter is the way to go. Alternatively, you can use _.where, which is essentially a shortcut for filtering on simple key/value pairs. The logic behind this can be found in the source code:

// Here is a convenient version of `filter` that selects only objects
// with specific `key:value` pairs.
_.where = function(obj, attrs, first) {
  if (_.isEmpty(attrs)) return first ? void 0 : [];
  return _[first ? 'find' : 'filter'](obj, function(value) {
    for (var key in attrs) {
      if (attrs[key] !== value[key]) return false;
    }
    return true;
  });
};

The documentation could provide more clarity, but the source code's comment explains it well.

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

Obtain the date in ISO format without subtracting the timezone offset

I need to obtain a Date string without the timezone being added or subtracted. Currently, when I set my OS timezone to GMT +13 and create a new Date() object, the toISOString() method subtracts one day. For example, today is 11/02. If I adjust my OS time ...

Develop and share a function to be assessed within a different scope's context in JavaScript

Currently, I'm exploring the use of angular and bootstrap tour and I have a challenge in trying to isolate objects within their own area without storing them in the controller. My goal is to store an object in the service, which also contains function ...

What is the best way to incorporate JSON data within a "data:{}" object when making a POST fetch request?

Greetings to all the listeners, this is my first time reaching out for help. I have put together a form and I am making a fetch request to my database system (Xano). Here is a snippet of how my JSON object looks: { "job_type": "full-time& ...

To effectively store the input values from eight labels into an array and subsequently identify the prime numbers within the array using JavaScript, follow these step-by-step instructions

As a newcomer to JavaScript, I am trying to extract the values of 8 labels (text) and store them in an array of 8 numbers. My goal is to then identify the prime numbers within this array. While I have been able to create the array and display the labels in ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...

JavaScript popup displaying incorrectly

In my experience, I have completed two web-related classes that involved similar projects with popups using HTML and JavaScript. However, I am facing an issue where the popup either does not show at all or appears for only a brief moment before closing its ...

How to perfectly center a background image using CSS

I am currently working on a project that involves using a background image. However, I am facing some difficulties in trying to fully center the image, similar to what is shown in this My objective is https://i.sstatic.net/XUNTy.png What I have achieved s ...

Avoid reloading the page in PHP when the browser back button is clicked

I've built an HTML form where the values are passed to a second page using POST method. On the second page, I have an edit button that, when clicked, redirects back to the HTML form page with the user's typed values. However, my dilemma is figuri ...

How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening? getUserProfile() { uni.getLocation({ type: 'gcj02 ', geocode: true, success: (res) => ...

Is it possible for mesh1 and mesh2 to automatically adjust their positions based on scale?

I have a goal to connect the right side of mesh 1 with the left side of mesh 2. Whenever I scale mesh 1, it requires me to readjust the position of mesh 2 in order to maintain the original distance between them. Let's try scaling mesh 1 by setting z ...

How to prevent links from being affected by the Gooey effect in D3

Issue: When applying the Gooey effect, the links are also affected, resulting in a teardrop shape instead of a circle. The code snippet includes a dragged() function that allows users to detach node 1 from node 0 and reconnect them by dragging. The code s ...

What could be causing my ng-class specified directive to not be recognized in AngularJS?

check out this plunker link I am facing a challenge where I need to incorporate a directive as a class in my code. Specifically, I want to use the following pattern: ng-class='{"some-directive":1'} However, the directive can only be registered ...

Ways to integrate mouse out functionalities using an if condition

I'm currently working on a menu using Javascript where clicking on one option will dim the other options and reveal a sub-menu. I'm looking to include an if statement in the function so that when a user mouses out of both the sub-menu and the cli ...

What is the best way to have setState function properly within setInterval? (currently functioning somewhat)

function timerFunction(){ const [time, setTime] = useState(10); var timeRemaining = 10; const myInterval = setInterval(() => { if (timeRemaining > 0) { timeRemaining = timeRemaining - 1; setTime(timeRemaining); } els ...

Working with Vue.js and Axios: Extracting data from a nested Axios response

I am currently working on a project that involves Vue.js, TypeScript, and Axios. My main focus is on creating a complex ApiRequest. Unlike the traditional method of fetching data using axios directly in the component, I wanted to find a more maintainable s ...

Incapable of deactivating button in Vue JS when quantity equals zero

I'm currently working with Vue to create a quantity selector component where users can increase or decrease input values. However, I am facing an issue where I need to disable the minus button when the value is zero or lower. Below is the HTML and JS ...

Generate a progress indicator upon user clicking a hyperlink

I am looking to implement a loading bar that appears when the user clicks a link. Additionally, I need to upload data (via Ajax) into div#work if needed, followed by displaying the loading bar. Once the data is successfully uploaded, I want the script to s ...

The functionality of a generated button has been compromised

My goal is to create a webshop that doesn't rely on MySQL or any database, but instead reads items from JSON and stores them in LocalStorage. However, I've encountered an issue where the functionality of buttons gets lost after using AJAX to gene ...

Are there Variances in Performance Between Non-Concurrent Async Loops and Synchronous Loops in Node.js?

Recently, I took on the task of refactoring JavaScript code for Node.js (v10.13.0) that was originally synchronous and transformed it into asynchronous code using async/await. Surprisingly, after making this change, I observed a significant 3x slowdown in ...

Tips for sending dynamic column and row information to antd table

https://i.sstatic.net/XY9Zt.png The following code does not seem to work for an array containing rows and columns Below is an example using antd: const data = []; for (let i = 0; i < 4; i++) { data.push({ key: i, name: `Edward King ${i}`, ...