1

I am building a javascript function where I want to add an object to an array IF it is not already present, if it is I just want to update value.

My objects look like this:

[{31652237148248: 12}, {4365124714824: 4}]

How can I check the Array if there is an object with the ID of 31652237148248?

I tried this but it did not work:

var index = cartItems.findIndex((obj => obj[id] == id));
2
  • Your code is looking to see if the id is equal to the value of the object.... Commented Nov 21, 2019 at 22:31
  • It is used for Shopify cart Commented Nov 21, 2019 at 23:04

3 Answers 3

5

Use the in operator to check if the id is a property of the object:

const cartItems = [{31652237148248: 12}, {4365124714824: 4}];

const id = '4365124714824';

const index = cartItems.findIndex((obj => id in obj));

console.log(index);

Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly fine!
2

You are looking to see if the value of objects property is equal to the id. 31652237148248 is never going to equal 12

so you can just do a type of

var index = cartItems.findIndex(obj => typeof obj[id] !== undefined);

you can do a truthy check - will fail if it is a falsey value.

var index = cartItems.findIndex(obj => obj[id]);

you can use object keys and includes or if first is equal

var index = cartItems.findIndex(obj => Object.keys(obj).includes(id));
var index = cartItems.findIndex(obj => Object.keys(obj)[0] === id);

A bunch of ways to do it

Personally a better way is just to use an object and not an array for the data.

var items = {31652237148248: 12, 4365124714824: 4}

const addItem = (id, count) => {
  cartItems[id] = (cartItems[id] || 0) + count
}

const getArray = () => 
  Object.entries(items).map(([key, count]) => ({ [key]: count }))

Comments

1

Try

let add = (obj,arr,k=Object.keys(obj)[0]) => 
           arr.some( o=> (k in o)&&(o[k]=obj[k]) ) || arr.push(obj) 

let data = [{31652237148248: 12}, {4365124714824: 4}]

let add = (obj,arr,k=Object.keys(obj)[0]) => 
           arr.some( o=> (k in o)&&(o[k]=obj[k]) ) || arr.push(obj) 

// TEST
add({31652237148248: 15}, data);
console.log('update',data);

add({666: 15}, data);
console.log('add',data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.