BHAR4T
BHAR4T

Reputation: 334

Comparing two Arrays.map values dynamically

I have two arrays first array Deals contains deal list where it has dealId, buyerId, sellerId and, the second array Customer contains customers list where it has customerId, name. I just want to compare Deal.sellerId to Customer.customerId and want to show the Customer.name.

Don't confuse with the <DealDetail /> its a component which has attribute sellerName, for this component I want customer name value.

Deals Array:

this.state.updatedDeals.map(deal => <DealDetail key={deal.id} dealID={deal.id} sellerName={deal.sellerId} buyerName={deal.buyerId} />)

Customers Array:

this.state.updatedCustomers.map(customer => <li key={customer.id} > {customer.name} </li>)>

What I exactly wanting:

<DealDetail sellerName={deal.sellerId===customer.customerId ? customer.name} : "Unknown" />)

Upvotes: 1

Views: 280

Answers (3)

BHAR4T
BHAR4T

Reputation: 334

Fetched data from firestore:

updatedCustomers[doc.id] = doc.data();

And solved above problem with this:

this.state.updatedDeals.map(deal => (<DealDetail key={deal.id}

         sellerName={this.state.updatedCustomers[deal.sellerId].name}
         buyerName={this.state.updatedCustomers[deal.buyerId].name}

       />))

Upvotes: 0

Isaac
Isaac

Reputation: 12874

let updatedDeals = [
  {dealId: 10, buyerId: 1, sellerId: 26},
  {dealId: 11, buyerId: 1, sellerId: 26},
  {dealId: 12, buyerId: 1, sellerId: 27},
];

let updatedCustomers = [
  {customerId: 26, customerName: 'Isaac'},
  {customerId: 28, customerName: 'Jane'}
];

let DealDisplay = [];

updatedCustomers.forEach(cust => {
  if(updatedDeals.some(deal => deal.sellerId === cust.customerId)){
    DealDisplay.push(cust);
  }
});

Why not separate the logic in order to promote maintainability and readability. You can extract the records into a separate array as temporary variable. Then render the view using the variable

Upvotes: 1

Vineesh
Vineesh

Reputation: 3782

You can try something like below.

this.state.updatedDeals.map(
    (deal) =>
    { 
        const c =   this.state.updatedCustomers.filter(customer=>deal.sellerId===customer.id);
        <DealDetail 
            key={deal.id} 
            dealID={deal.id}        
            sellerName={c.length ==1 ? c[0].name:'unknown'} 
            buyerName={deal.buyerId} 
        />
    }
)

Upvotes: 1

Related Questions