var array = [];
Now, I am creating an object with post requests.
var object = {
property 1: req.body.x;
property 2: req.body.y
};
if the property 1 value(i.e. req.body.x
) already exists in any of the objects in the array, it should giving a warning. Else we need to do array.push(object)
.
How to check for the property 1 value every time with the post request.
CodePudding user response:
You can use array.Find in order to check if an object exists in the array with the same property.
const arr = [{
prop1: 'foo', // prop1 of `foo` already in array
}]
// small function so we can avoid code duplication
const existsInArray = (obj) => {
return arr.find((a) => a.prop1 === obj.prop1)
}
const obj1 = {
prop1: 'foo',
}
const obj2 = {
prop1: 'bar',
}
if (existsInArray(obj1)) {
console.warn('obj1 already in array')
} else {
arr.push(obj1)
}
if (existsInArray(obj2)) {
console.warn('obj2 already in array')
} else {
arr.push(obj2)
}
console.log(arr)