user1486133
user1486133

Reputation: 1477

Search an object for associated data

I have an object like so:

var products = {"products":[
    {"productID":"32652", "name":"Playstation 4", "price":"109.99"},
    {"productID":"24164", "name":"Xbox", "price":"129.99"}
]};

I need to search with the variable productID and find the associated name and price

My searches have just led me off track with things like .closest which is for the DOM not for an object.

How can I search the object for the productID var and find the associated data?

Upvotes: 1

Views: 48

Answers (4)

Samer Ayoub
Samer Ayoub

Reputation: 1001

console.log(products.products.find(function(p) {return p.productID === '24164'}));

Upvotes: 0

Samer Ayoub
Samer Ayoub

Reputation: 1001

var products = {"products":[
   {"productID":"32652", "name":"Playstation 4", "price":"109.99"},
   {"productID":"24164", "name":"Xbox", "price":"129.99"}
]};

function findProduct(product) { 
   return product.productID === '24164';
}

console.log(products.products.find(findProduct)); //{productID: "24164", name: "Xbox", price: "129.99"}

Upvotes: 0

Sarantis Tofas
Sarantis Tofas

Reputation: 5167

You can use Array.prototype.filter()

var result = products.products.filter(function(obj) {
  return obj.name == "Xbox";
})[0];

Note that .filter will return an array. If you just need the first match then this will work for you. In case you need all the results then just remove the [0]

Upvotes: 1

Paarth
Paarth

Reputation: 10377

You can use array.find

var foundProduct = products.products.find(x => x.productId === "12345")
if (foundProduct) { // foundProduct can be undefined. 
    var foundName = foundProduct.name
    var foundPrice = foundProduct.price
} else { /* handle not found */ }

If you are in a context that doesn't support Array.find yet, you can use .filter instead which is more commonly implemented.

var foundProduct = products.products.filter(x => x.productId === "12345")[0]
if (foundProduct) { // foundProduct can be undefined. 
    var foundName = foundProduct.name
    var foundPrice = foundProduct.price
} else { /* handle not found */ }

Upvotes: 1

Related Questions