¿Cómo agrego un valor de una matriz a otra matriz para crear una nueva matriz?
Tengo dos matrices y quiero filtrar a través de arrayTwo find where id === productID from arrayOne . Luego agregue la quantity de arrayOne a arrayTwo para que pueda obtener un resultado como arrayThree
arrayOne = [ { productID: "DuWTLdYkpwF1DJ2x8SGB", quantity: 2 }, ] arrayTwo = [ { id: "DuWTLdYkpwF1DJ2x8SGB", minQuantity: 1, name: "5 Shade Palette", price: "950", size: "30g", unitPrice: 950, }, ]Resultado buscado::
arrayThree = [ { id: "DuWTLdYkpwF1DJ2x8SGB", minQuantity: 1, name: "5 Shade Palette", price: "950", size: "30g", unitPrice: 950, quantity: 2, }, ]Puede fusionar los dos objetos fácilmente usando el operador de extensión:
arrayOne = [ { productID: "DuWTLdYkpwF1DJ2x8SGB", quantity: 2 }, ] arrayTwo = [ { id: "DuWTLdYkpwF1DJ2x8SGB", minQuantity: 1, name: "5 Shade Palette", price: "950", size: "30g", unitPrice: 950, }, ] console.log({...arrayOne[0], ...arrayTwo[0]})Use esto en combinación con su filtro inicial y debería tener lo que desea. Sin embargo, recomendaría usar 'find()' en su lugar.
Esto se verá algo como esto:
// Loop every item of one array arrayOne.forEach( (product) => { // Find linked product let productToMerge = arrayTwo.find(p => p.productID === product.productID) // Let's merge them let newItem = {...product, ...productToMerge} })Ahora solo es cuestión de empujar este elemento nuevo en una matriz para recopilar todos los elementos nuevos.
La complejidad del tiempo es O (n ^ 2) aquí. Si las matrices dadas son realmente largas, no es la mejor opción. Básicamente: para cada elemento en arrayOne , encuentre su par en arrayTwo y combínelos.
let arrayThree = arrayOne.map(first => { return { ...first, ...arrayTwo.find(second => second.id == first.productID) } });A continuación se muestra una forma posible de lograr el objetivo.
Fragmento de código
// add "quantity" to existing products const addDeltaToBase = (delta, base) => ( // iterate over the "base" (ie, existing product array) base.map( ({ id, ...rest }) => { // de-structure to access "id" // check if "id" is part of the delta (to update "quantity") const foundIt = delta.find(({ productID }) => productID === id); if (foundIt) { // found a match, so update "quantity return ({ id, ...rest, quantity: foundIt.quantity }) }; // control reaches here only when no match. Return existing data as-is return { id, ...rest } } ) // implicit return from "base.map()" ); const arrayOne = [ { productID: "DuWTLdYkpwF1DJ2x8SGB", quantity: 2 }, ]; const arrayTwo = [ { id: "DuWTLdYkpwF1DJ2x8SGB", minQuantity: 1, name: "5 Shade Palette", price: "950", size: "30g", unitPrice: 950, }, ]; console.log(addDeltaToBase(arrayOne, arrayTwo)); .as-console-wrapper { max-height: 100% !important; top: 0 }Explicación
Comentarios en línea agregados en el fragmento anterior.
NOTA
arrayOne como arrayTwo con múltiples objetos.productId con id y, cuando coincide, fusiona la quantity en la salida (es decir, arrayThree ).