Check If Object Value Exists Within a JavaScript Array of Objects and If Not Add a New Object to Array

How to determine if object is in array

Use something like this:

function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}

return false;
}

In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}

return false;
}

This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

Check if object value exists within a Javascript array of objects and if not add a new object to array

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
function add(arr, name) { const { length } = arr; const id = length + 1; const found = arr.some(el => el.username === name); if (!found) arr.push({ id, username: name }); return arr;}
console.log(add(arr, 'ted'));

How to determine if Javascript array contains an object with an attribute that equals a given value?

2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.

There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.

var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}

How can I check if object exists in array of objects and update quantity?

You need to check all objects and exit the function if one item is found for incrementing the quantity.

If not found push the object.

var objArray = [{ name: "bike", color: "blue", qty: 2 }, { name: "boat", color: "pink", qty: 1 }],    carObj = { name: "car", color: "red", qty: 1 },    bikeObj = { name: "bike", color: "blue", qty: 1 };  function checkAndAdd (obj) {    for (var i = 0; i < objArray.length; i++) {        if (objArray[i].name === obj.name) {            objArray[i].qty++;            return;                             // exit loop and function        }    }    objArray.push(obj);}
checkAndAdd(carObj);console.log(objArray);
checkAndAdd(bikeObj);console.log(objArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Check if one element exists in an array of objects

I think this may help

let resultArray=memberships.filter(function(item) {
return item["type"] === 'member';
});

the result array holds the data of the objects that has type member

How to check if a specific object already exists in an array before adding it

If your object is created earlier and has the same reference as the one in the array, you can use indexOf:

var myObj = { a: 'b' };
myArray.push(myObj);
var isInArray = myArray.indexOf(myObj) !== -1;

Otherwise you can check it with find:

var isInArray = myArray.find(function(el){ return el.id === '123' }) !== undefined;

Javascript check if object by Id is in array

let id = 3;
const arr = [{
id: 1,
name: 'James'
}, {
id: 2,
name: 'Peter'
}, {
id: 3,
name: 'Mike'
}]

var chek = arr.find(c => c.id === id);

console.log(chek ?? "Not present")
//or:
if (chek === undefined) {
console.log("Not present")
} else {
console.log(chek.name)
}

Update or add new element to array of objects and update array in object if value exists

You were already pretty close, just made some small errors like not filtering out the object you want to update from the array. I did also change it to use find instead of findIndex but it does not make a huge difference.

function updateSelectedValues(selectedValues: SelectedValues[], valueGroup: string, value: string): SelectedValues[] {
// If array empty add first object
if (selectedValues.length === 0) {
return [{ valueGroup: valueGroup, values: [value] }];
} else {
// look if valueGroup is already there
const obj = selectedValues.find((find) => find.valueGroup === valueGroup);
if (!obj) {
// if no add new valueGroup with first values
return [...selectedValues, { valueGroup: valueGroup, values: [value] }];
} else {
if (obj.values.includes(value)) {
// yes, remove value from values
return [...selectedValues.filter((object) => object.valueGroup !== valueGroup), { ...obj, values: obj.values.filter((filter) => filter !== value) }];
} else {
// no, add value to values
return [
...selectedValues.filter((object) => object.valueGroup !== valueGroup),
{ ...obj, values: [...obj.values, value] },
];
}
}
}
}

The above shows where you went wrong in your implementation. However we could simplify it to be this:

function updateSelectedValuesLight(selectedValues: SelectedValues[], valueGroup: string, value: string): SelectedValues[] {
const obj = selectedValues.find((value) => value.valueGroup === valueGroup);

if (!obj) return [...selectedValues, {valueGroup, values: [value]}];

if (obj.values.includes(value)) {
obj.values = [...obj.values.filter(iValue => iValue !== value)];
} else {
obj.values = [...obj.values, value];
}

return selectedValues;
}

This Playground has some tests to see the functionality.



Related Topics



Leave a reply



Submit