Verify whether the value of the Object matches the value of the string

Currently, I have a situation in ES6 where I am utilizing Vue.js for the current module.

The task at hand is to verify if a specific string value exists within an array object.

let obj1 = [{name: "abc ced", id: 1},
           {name: "holla' name", id: 2},
           {name: "3' name", id: 3}]
let obj2 = { key: "3' name" , key1: 2 }

The goal is to retrieve the object from obj1 where the name property value of obj2 can be found in obj1. Here's how it's being attempted:

 _.each(obj1, function(obj){
     for (var k in obj) {
        if (!obj.hasOwnProperty(k)) continue
            if (obj[k] === obj2.key) {
                  console.log(obj)
            }
         }
   })

Is something being overlooked? The console never seems to log any values.

Important to note:

I am making use of lodash, and even tried using the find method as well.

 let result = _.find(obj1 , {name: obj2.key})
 console.log(result)

This approach works perfectly when trying:

let result = _.find(obj1 , {id: obj2.key1})
console.log(result)

So, integer matches work fine, but there are issues with strings not appearing on the console. I then tried other solutions as mentioned above.

Note: Initially everything seemed to be functioning correctly, except that I forgot to consider string case sensitivity. There were some uppercase and capitalized words causing problems. It's important to convert comparable strings to lower or uppercase so as to avoid such mistakes.

Cheers!

Answer №1

To retrieve the first object that satisfies a certain condition, you can utilize the find() method. Alternatively, if you want to find all objects that meet the criteria, you can employ the filter() method.

const obj1 = [{name: 'abc ced', id: 'ced'},
           {name: 'holla name', id: 'xyz'}]
const obj2 = { key: 'abc ced' }

const result = obj1.find(({name}) => obj2.key === name)
console.log(result)

Answer №2

You have the option of utilizing lodash's _.find function. For more information, check out lodash find.

let obj1 = [
    { name: "abc ced", id: "ced"},
    { name: "holla' name", id: "xyz"},
    { name: "3' name", id: "xz"},
    { name: 5, id: "yz"}
];
let obj2 = { key: "3' name" }
let obj3 = { key: 5 }

var result = _.find(obj1, { name: obj2.key });
console.log(result)

var result = _.find(obj1, { name: obj3.key });
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f29e9d9693819ab2c6dcc3c5dcc6">[email protected]</a>/lodash.min.js"></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

Is there a way to incorporate a trace in Plotly while also arranging each data point along the x-axis in a unique custom order?

I am facing a challenge in creating a line graph that displays (x, y) coordinates where the x axis represents a date and the y axis represents a value. The dates are formatted like DD-MM-YYYY, for example, 15-04-2015. My initial trace is added with the fo ...

Using Ajax and jQuery to Retrieve the Value of a Single Tag Instead of an Entire Page

Let's say I have a webpage named page.html: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Page</title> </head> <body> <h1>Hello World!!</h1> </body> </html> Now ...

UI-grid: Triggering a modal window from the filter header template

Is there a way to create a filter that functions as a simple modal window triggered by a click event, but can be displayed on top of a grid when placed within the filterHeaderTemplate? I have encountered an issue where the modal window I created is being ...

Real-time changes may not be instantly reflected in the model update

I need to add two numbers together and display the sum in a third input field: HTML <div ng-app="myApp"> <div ng-controller="MainCtrl as mainCtrl"> Main {{mainCtrl.foo}} <br/> <input type="text" ng-model="mainCtrl.foo"/> ...

The return false statement is failing to execute properly within this particular JavaScript function

I'm encountering an issue with my onclick function: $("#mymodal").on("click",".close",function() { checkpincode(); checkzipcode(); }); Even though the fn checkpincode returns false, the execution still proceeds and my checkzipcode function i ...

Intercommunication of variables among components

My scenario involves two components, namely App and SomeComponent. I'm aiming to access a variable in App from SomeComponent. App: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css& ...

The react-redux developer tool appears to be disabled and is not displaying the current state of the application on the extension toolbar

Just finished the redux-tutorial and attempting to view the state in the redux-devtools. However, the redux-devtools seems to be inactive on the extensions bar. Upon clicking it, a menu appears with options like "to right, to left etc". Selecting one of ...

Looking for a way to create a regular expression that can parse an email response containing the newline character?

Do you need help parsing only the most recent reply from the email thread below? For example, Hello Nikhil Bopora,↵↵Just to give a brief, I am in process of building an alternate e-lending↵platform. I tried using the general regex /[\s]*([&bsol ...

Is there a way to calculate the total of three input values and display it within a span using either JavaScript or jQuery?

I have a unique challenge where I need to only deal with positive values as input. var input = $('[name="1"],[name="2"],[name="3"]'), input1 = $('[name="1"]'), input2 = $('[name="2"]'), input3 = $('[name=" ...

Struggling to Implement Insertion Sort with JSON Data

public class ReverseList extends HttpServlet { public static void sort(int arr[]) { int N = arr.length; int i, j, temp; for (i = 1; i< N; i++) { j = i; temp = arr[i]; while (j > 0 && temp &l ...

Separate the information into different sets in JavaScript when there are more than two elements

Upon extraction, I have obtained the following data: ╔════╦══════════════╦ ║ id ║ group_concat ║ ╠════╬══════════════╬ ║ 2 ║ a ║ ║ 3 ║ a,a ...

Numerous toggles paired with various forms and links

I am currently facing an issue with toggling between forms on my website. Although the toggle functionality works fine, I believe I may have structured the steps in the wrong order. My ideal scenario is to display only the 'generating customer calcul ...

Checking an array of objects for validation using class-validator in Nest.js

I am working with NestJS and class-validator to validate an array of objects in the following format: [ {gameId: 1, numbers: [1, 2, 3, 5, 6]}, {gameId: 2, numbers: [5, 6, 3, 5, 8]} ] This is my resolver function: createBet(@Args('createBetInp ...

What is the best way to utilize a variable across all functions and conditions within an asynchronous function in Node.js?

I need to access the values of k and error both inside and outside a function. Initially, I set k to 0 and error to an empty string, but unexpectedly, the console prints out "executed". var k = 0; var error = ""; const { teamname, event_name, inputcou ...

Using jQuery to Save Data Locally in a JSON File

Just a heads up; all of my work is kept local. I've been on the hunt for ways to write to a JSON file from a JS script using jQuery. Many methods involve PHP, but I don't have much experience with that language and would prefer to avoid it for no ...

During the serialization process, a circular reference was identified within an object of the type 'SubSonic.Schema.DatabaseColumn'

I'm attempting to perform a simple JSON return, but I'm encountering some issues with the code below. public JsonResult GetEventData() { var data = Event.Find(x => x.ID != 0); return Json(data); } When I run this code, I receive a HT ...

Tips for removing Blogger post snippet code from the template below:

Check out my blog at: . I have also posted the full Template code at https://pastebin.com/GXuPFKzH I want to display the full post on the homepage instead of just a snippet. Can you help me figure out which code needs to be removed? [insert image of the ...

Efficient arrow function usage in jQuery map functionality

Looking to implement an arrow function in jQuery's map function. However, after trying the following code snippet, titlesText ends up being the correct length but with empty strings: let titles = $(panelBody).find('h4'); let titlesText = $(t ...

What could be causing BeautifulSoup to overlook certain elements on the page?

For practice, I am in the process of developing an Instagram web scraper. To handle dynamic webpages, I have opted to utilize Selenium. The webpage is loaded using: driver.execute_script("return document.documentElement.outerHTML") (Using this javascript ...

Using Grails to create remote functions with multiple parameters

Currently, I am able to send one parameter to the controller using the code snippet below in Javascript: <g:javascript> var sel = "test"; <g:remoteFunction action="newExisting" method="GET" update="updateThis" params="'sel='+s ...