var arr = [ { id:1}, {id:2} ];
var obj = {id:1};
var result = arr.indexOf(obj.id) == -1;
console.log(result);
I am trying to determine if obj.id
exists in the array arr[]
.
Please note: arr[]
is an array of objects
var arr = [ { id:1}, {id:2} ];
var obj = {id:1};
var result = arr.indexOf(obj.id) == -1;
console.log(result);
I am trying to determine if obj.id
exists in the array arr[]
.
Please note: arr[]
is an array of objects
Give this a shot...
var array = [{ id:1}, {id:2}];
var target={id:1};
var idsArray = array.map(function(obj){
return obj.id
}); // create an array of all ids
var found = idsArray.indexOf(target.id) != -1 // check if target id is in array
console.log(found);
Here's a solution that should function correctly:
const items = [{ id: 1 }, { id: 2 }];
const query = { id: 1 };
console.log(items.findIndex(item => item.id === query.id));
The indexOf method is useful for indexed arrays but may not work as expected when dealing with arrays of objects.
Kindly make use of the code snippet below:
var arr = [ { id:1}, {id:2} ];
var obj={id:1}
function searchMatch(item) {
return item.id === obj.id;
}
console.log(arr.findIndex(searchMatch));
An alternative approach is to utilize the .find
method.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
obj = a.find(function(itm) {
return itm.id == b.id;
});
console.log(obj)
Another useful function is .findIndex
, which returns the index of an item in the array.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
objIndex = a.findIndex(function(itm) {
return itm.id == b.id;
});
console.log(objIndex)
To retrieve all objects that meet a certain condition, you can employ the .filter
function.
let a = [{
id: 1
}, {
id: 2
}],
b = {
id: 1
},
objArr = a.filter(function(itm) {
return itm.id == b.id;
});
console.log(objArr)
In the Array.map() function, it compares the ID and its value, returning a Boolean value if the map is present, as highlighted by @Slava Utesinov.
var array = [{id: 1}, {id: 2}];
var obj = {id: 1};
if(array.map(item => item.id).indexOf(obj.id) != -1){
console.log("Exists");
}else{
console.log("Does not exist");
}
give this a shot
let animals = [ { name:"lion", sound: "roar" }, {name:"dog", sound: "bark"} ];
let chosenAnimal = {name: "lion"};
console.log(animals.find(animal => animal.name === chosenAnimal.name)) // returns matched record
let animals = [{ name: "elephant", size: "large" }];
let chosenAnimal = { name: "giraffe" };
console.log(animals.find(animal => animal.name === chosenAnimal.name)) // returns undefined
To verify, you can utilize the Array.map() method in JavaScript. This function will compare the id
property and its corresponding value
.
Here is a snippet of functional code:
var array = [{
id: 1
}, {
id: 2
}];
var obj = {
id: 1
};
if (array.map(item => item.id).indexOf(obj.id) != -1) {
console.log("Item exists");
} else {
console.log("Item does not exist");
}
If you're working with AngularJS, utilizing the Filter feature can be helpful.
var array1 = [{id:1}, {id:2}];
var object1 = {id:1};
var isFound = false;
var filteredResult = $filter('filter')(array1, {id: object1.id}, true);
if (filteredResult.length > 0) {
isFound = true;
}
I have a list of data that I want to structure in Firebase. However, I encountered an error: Error: Firebase.child failed: The first argument provided is not a valid path. Path names should not include ".", "#", "$", "[", or "]" characters and must be no ...
I am facing challenges in writing a custom element directive. This directive, which I'll name myElement, generates multiple textarea or input fields based on certain parameters and applies ngModels to those fields. In addition, I want to be able to s ...
Is there a way to achieve the following scenario: var foo = function(){ this.value = 1; } var bar = "foo"; var baz = new bar(); alert(baz.value) // 1 Specifically, I am looking for a method to instantiate an object using its string name. Any sugge ...
I have a plan to create my own specialized react component library. These components will mainly focus on implementing specific logic rather than being full-fledged UI components. One key requirement is that users should have the flexibility to define a se ...
Disclaimer: This issue pertains to singleton objects in Node.js and not DB pools. While developing an Express.js application with the mysqljs node module for DB connections, I am interested in creating a single pool object that can be reused across differ ...
Is there a way to edit an array of objects in AngularJS, linked to the view through ng-repeat, without updating the scope until all objects have been modified? Consider this scenario: I need to update each object in the array and only then reflect the ch ...
I have a dilemma involving 10 images located in my public directory that I need to use in a component. Instead of individually importing each image like this: import imgurl1 from "../../public/celsius.gif"; import imgurl2 from "../../public/ ...
Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...
How can I use jQuery.find() to specifically target only the direct children of an element without selecting their descendants? Leading the selector with '>' or using '*' doesn't give me the desired result. While I know about jQuer ...
Currently, I am in the process of generating a map that will display various points using Mapbox and WordPress. To achieve this, I have set up a custom post type within WordPress where the coordinates are stored in custom meta fields. Although the fields h ...
I am encountering an issue with a jQuery ajax request that I have set up. Here is the code: jQuery.ajax({ url: serverAddress+'php/product.php', type: 'GET', jsonpCallback: "callback7", dataType: 'jsonp', d ...
Recently, I was exploring the React new documentation here, where I came across this interesting piece of information: The context value mentioned here is a JavaScript object with two properties, one being a function. Whenever MyApp re-renders (for examp ...
When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...
Currently, I am in the process of developing a website for my university that will allow users to easily locate all available free food options on campus. My goal is to create a platform where food providers can register their events, have them saved in a ...
I've been attempting to create a toggle click event using the code below: HTML <a class="load" data-gallery="123456" style="cursor: pointer;"><h2><p>example</p></h2></a> <div id="123456"> </div> j ...
After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...
I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...
Check out my demo on JSFidle: https://jsfiddle.net/uniqueusername/example123/ In the chart, there is a noticeable pink box at the top. I'm trying to remove it. Some suggestions I found involved adding the following code: legend: { labels: { ...
While testing on my computer, I encountered an issue where my test would start successfully, but after opening and closing several Internet Explorer windows during the test, no new windows would open. There were no error messages displayed, and the test se ...
Upon reviewing the template, I noticed that there is code implemented to check if the client has the necessary version. This code performs certain actions based on whether or not the required version is available. Additionally, there seems to be an <obj ...