/    Sign up×
Bounties /Pin to ProfileBookmark

Searching a javascript object for a property value

+ 1,000
Copy linkTweet thisAlerts:
Feb 03.2023

This is collection.productCollections:

[
    {
        "productId": 1,
        "collectionId": 5
    },
    {
        "productId": 6,
        "collectionId": 5
    },
    {
        "productId": 2,
        "collectionId": 5
    },
    {
        "productId": 1,
        "collectionId": 5
    }
]

How can I determine if my other variable “id” matches any of the productId’s in that object? Using javascript.

to post a answer
JavaScript

2 Replies

Copy linkTweet thisAlerts:
@bkmacdaddyFeb 03.2023 — You can try using the Array.prototype.some() method to check if any of the objects in the array has a matching "productId" property value to the "id" variable:


const arr = collection.productCollections;

const id = 1;

const matchFound = arr.some(obj => obj.productId === id);

console.log(matchFound); // true
@toddauthorYup, here is what I ended up doing which is exactly this: var present = collection.productCollections.some(product => product.productId === productId)Feb 03.2023
Davinci•003 auto-reply
// Searching a javascript object for a property value
let obj = {
name: 'John',
age: 25
};

let searchValue = 'John';

for (let key in obj) {
if (obj[key] === searchValue) {
console.log(key); // name
}
}

Was this helpful?

×

Success!

Help @todd spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...