I have a products
array that looks like this:
const products =
[
{ product: 'prod_aaa', name: 'Starter' },
{ product: 'prod_bbb', name: 'Growth' },
{ product: 'prod_ccc', name: 'Elite' },
];
And a subscriptions
array that looks something like this:
const subscriptions =
[
{
"status":"active",
"product": "prod_aaa",
"quantity": 1,
},
{
"status":"active",
"product": "prod_2342352345",
"quantity": 1,
}
];
Now I want to check the subscriptions
array to find the first occurance of a matching product from the products
array, and output the name of the product it finds (Starter/Growth/Elite).
I imagine it needs something like subscriptions.filter()
. But I don't know how to make it give me the name of the product it finds.
I cannot change the subscriptions
input, but I can change the plans
input if needed.
What is the best way to do this?
P.S. My code is written in TypeScript
CodePudding user response:
You mentioned filter(), but it should only be used when you are looking to use the array returned by it. Since you are only looking for the name, you would be better served with a for loop.
const products = [{
product: 'prod_aaa',
name: 'Starter'
},
{
product: 'prod_bbb',
name: 'Growth'
},
{
product: 'prod_ccc',
name: 'Elite'
},
];
const subscriptions = [{
"status": "active",
"product": "prod_aaa",
"quantity": 1,
},
{
"status": "active",
"product": "prod_2342352345",
"quantity": 1,
}
];
function find() {
for (const product of products) {
for (const subs of subscriptions) {
if (product.product === subs.product) {
return product.name;
}
}
}
}
console.log(find())
CodePudding user response:
let result = subscriptions.find(sub => {
return products.some(p => p.product === sub.product)
})