Kombinieren Sie zwei Arrays nach der Filtermethode


9

Ich sehe die Warenkorbseite nicht mehr, auf der die Produkte aufgelistet sind, die von Benutzern zum Warenkorb hinzugefügt wurden. Ich habe zwei Arrays: Eines mit den Produktdetails.

productDetails: [
            {
              productID: 1,
              productTitle: 'Product Title 1',
              productPrice: 2000
            },
            {
              productID: 2,
              productTitle: 'Product Title 2',
              productPrice: 5000
            },
            {
              productID: 3,
              productTitle: 'Product Title 3',
              productPrice: 1000
            },
            {
              productID: 4,
              productTitle: 'Product Title 4',
              productPrice: 10000
            }
          ],

Eine andere mit Warenkorb-Produktdetails, bei denen die Produkt-ID und die Menge nur von Benutzern ausgewählt wurden.

cartProducts: [
            {
              productID: 1,
              quantity: 5,
            },
            {
              productID: 3,
              quantity: 2,
            }
          ]

Ich habe alle vom Benutzer ausgewählten Produkte gefiltert.

cartItemDetails() {
      return this.productDetails.filter(
        el => this.cartProducts.some(f => f.id === el.productID),
      );
    },

Diese Funktion gibt die Produktdetails von productID 1 und 3 an. Ich möchte ein neues Array, das das Mengenattribut des cartProducts-Arrays zum productDetails-Array hinzufügt.

newArray: [
            {
              productID: 1,
              productTitle: 'Product Title 1',
              productPrice: 2000,
              quantity:5
            },
            {
              productID: 3,
              productTitle: 'Product Title 3',
              productPrice: 1000,
              quantity:5
            }
          ]

Ich hoffe ich habe meine Fragen klargestellt. Ich versuche auch, dieses Problem mit der Map-Javascript-Methode zu lösen, aber es funktioniert nicht.

Grüße,

Antworten:


3

Sie können map () after verwenden filter()und quantityjedem Element eine Eigenschaft hinzufügen .

const productDetails = [{ productID: 1, productTitle: 'Product Title 1', productPrice: 2000 }, { productID: 2, productTitle: 'Product Title 2', productPrice: 5000 }, { productID: 3, productTitle: 'Product Title 3', productPrice: 1000 }, { productID: 4, productTitle: 'Product Title 4', productPrice: 10000 }];
const cartProducts = [{ productID: 1, quantity: 5 }, { productID: 3, quantity: 2 }]; 

function cartItemDetails() {
  return productDetails
    .filter(el => cartProducts.some(f => f.productID === el.productID))
    .map(item => ({
      ...item,
      "quantity": cartProducts.find(f => f.productID === item.productID).quantity
    }));
}

console.log(cartItemDetails());

Oder Sie können redu () verwenden .

const productDetails = [{ productID: 1, productTitle: 'Product Title 1', productPrice: 2000 }, { productID: 2, productTitle: 'Product Title 2', productPrice: 5000 }, { productID: 3, productTitle: 'Product Title 3', productPrice: 1000 }, { productID: 4, productTitle: 'Product Title 4', productPrice: 10000 }];
const cartProducts = [{ productID: 1, quantity: 5 }, { productID: 3, quantity: 2 }]; 

function cartItemDetails() {
  return productDetails.reduce((acc, curr) => {
    let item = cartProducts.find(f => f.productID === curr.productID);

    if (item) {
      acc.push({ ...curr,
        "quantity": item.quantity
      });
    }

    return acc;
  }, []);
}

console.log(cartItemDetails());

Sie können auch map()auf verwenden cartProducts.

const productDetails = [{ productID: 1, productTitle: 'Product Title 1', productPrice: 2000 }, { productID: 2, productTitle: 'Product Title 2', productPrice: 5000 }, { productID: 3, productTitle: 'Product Title 3', productPrice: 1000 }, { productID: 4, productTitle: 'Product Title 4', productPrice: 10000 }];
const cartProducts = [{ productID: 1, quantity: 5 }, { productID: 3, quantity: 2 }]; 

function cartItemDetails() {
  return cartProducts.map(item => ({
    ...productDetails.find(f => f.productID === item.productID),
    ...item
  }));
}

console.log(cartItemDetails());


Sehr geschätzt. Vielen Dank für verschiedene Antworten. Ich akzeptiere diese Antwort unter anderem aufgrund ihrer Methodenvielfalt. Vielen Dank
Sujan Shrestha

Gern geschehen @SujanShrestha. Ich bin froh, dass es geholfen hat.
Nikhil

4

Verwenden Sie Map und Object Spread, um die beiden Arrays zu kombinieren:

var newArray = cartProducts.map(cart => ({
  ...cart,
  ...productDetails.find(prod => prod.productID === cart.productID)
}));

Vielen Dank für Ihre Antwort. Sehr geschätzt.
Sujan Shrestha

Bitte. Gutes Aussehen mit Ihrem Projekt.
Jaspenlind

4

Konvertieren Sie das productDetailsin eine Map ( productDetailsMap), indem Sie das productIDals Schlüssel verwenden.

Iterieren Sie das cartProductsmit, Array.map()um das aktuelle Produkt productDetailsMapzu erhalten productID, und verschmelzen Sie es, indem Sie es in ein neues Objekt ausbreiten .

const productDetails = [{"productID":1,"productTitle":"Product Title 1","productPrice":2000},{"productID":2,"productTitle":"Product Title 2","productPrice":5000},{"productID":3,"productTitle":"Product Title 3","productPrice":1000},{"productID":4,"productTitle":"Product Title 4","productPrice":10000}]
const cartProducts = [{"productID":1,"quantity":5},{"productID":3,"quantity":2}]

const productDetailsMap = new Map(productDetails.map(o => [o.productID, o]))

const result = cartProducts.map(o => ({
  ...productDetailsMap.get(o.productID),
  ...o
}))

console.log(result)


1
Vielen Dank für den sauberen Code. Ihre Antwort ist so sauber und einfach. Vielen Dank
Sujan Shrestha

3

Sie können etwas Ähnliches ausprobieren:

cartItemDetails() {
    return this.cartProducts.map(cp => {
         let prod = this.productDetails.find(pd => pd.productID === cp.productID)
         return {...cp, ...prod}
    })
}

Hoffe das hilft :)


Vielen Dank für Ihre Antwort. Sehr geschätzt.
Sujan Shrestha

3

Mit der Object.assign()Methode können Sie Eigenschafts-Wert-Paare aus productDetails in cartProducts kopieren, wenn die productID übereinstimmt:

let productDetails = [
            {
              productID: 1,
              productTitle: 'Product Title 1',
              productPrice: 2000
            },
            {
              productID: 2,
              productTitle: 'Product Title 2',
              productPrice: 5000
            },
            {
              productID: 3,
              productTitle: 'Product Title 3',
              productPrice: 1000
            },
            {
              productID: 4,
              productTitle: 'Product Title 4',
              productPrice: 10000
            }
          ];

let cartProducts = [
            {
              productID: 1,
              quantity: 5,
            },
            {
              productID: 3,
              quantity: 2,
            }
          ];
cartProducts.map(cart => Object.assign(cart, productDetails.find(product => product.productID === cart.productID))  )
console.log(cartProducts)


1
Vielen Dank für Ihre Antwort. Sehr geschätzt.
Sujan Shrestha

3
cartProducts.map(cartProduct => {
  return {
    ...productDetails.find(product => product.productID === cartProduct.productID),
    "quantity": cartProduct.quantity
  }
});

Bei Bedarf können Sie einige Nullprüfungen durchführen.


Vielen Dank für Ihre Antwort. Sehr geschätzt.
Sujan Shrestha

3

Dies ist, was Ihren Code hier durcheinander bringt:

cartItemDetails() {
      return this.productDetails.filter(
        el => this.cartProducts.some(f => f.id === el.productID),
      );
    },

fDas ist ein cartProductsArtikel hat keine Eigenschaft id.

Ich denke, was du gemeint hast, ist f.productIDstattdessen.

Hier ist eine Möglichkeit, die quantityEigenschaft mithilfe der mapFunktion hinzuzufügen :

this.productDetails = cartItemDetails().map((element) => {
  for (let e of this.cartProducts) {
    if (e.productID === element.productID) return {...element, quantity: e.quantity}
  }
})

Array cartProducts hatte ein ID-Element in meinem lokalen Code. Beim Posten der Frage habe ich sie geändert, um sie klarer zu machen. Und danke für deine Antwort.
Sujan Shrestha
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.