Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

94
Vistas
Nested array issue in JavaScript

I have the following array

Array["MyArray",
  {
      "isLoaded":true,
      "items":
      [{
          "id":"4",
          "name":"ProductA",
          "manufacturer":"BrandA",
          "quantity":1,
          "price":"25"
      },{
          "id":"1",
          "name":"ProductB",
          "manufacturer":"BrandB",
          "quantity":5,
          "price":"20"
      }],
      "coupons":null
  }
 ]

I need to load product names and their quantity from the array.

const result = [key, value].map((item) => `${item.name} x ${item.quantity}`);
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Here's one possible way to achieve the desired result:

const getProductsAndQuantity = ([k , v] = arr) => (
    v.items.map(it => `${it.name} x ${it.quantity}`)
);

How to use it within the context of the question?

localforage.iterate(function(value, key, iterationNumber) {
  console.log([key, value]);
  const val2 = JSON.parse(value);
  if (val2 && val2.items && val2.items.length > 0) { 
      console.log(val2.items.map(it => `${it.name} x ${it.quantity}`).join(', '))
  };
});

How it works?

  1. Among the parameters listed in the question ie, value, key, iterationNumber, only value is required.
  2. The above method accepts the key-value pair as an array (of 2 elements) closely matching the console.log([key, value]); in the question
  3. It uses only v (which is an object). On v, it accesses the prop named items and this items is an Array.
  4. Next, .map is used to iterate through the Array and return each product's name and quantity in the desired/expected format.

Test it out on code-snippet:

const arr = [
  "MyArray",
  {
    "isLoaded": true,
    "items": [{
      "id": "4",
      "name": "ProductA",
      "manufacturer": "BrandA",
      "quantity": 1,
      "price": "25"
    }, {
      "id": "1",
      "name": "ProductB",
      "manufacturer": "BrandB",
      "quantity": 5,
      "price": "20"
    }],
    "coupons": null
  }
];

const getProductsAndQuantity = ([k, v] = arr) => (
  v.items.map(
    it => `${it.name} x ${it.quantity}`
  )
);

console.log(getProductsAndQuantity());

about 4 years ago · Juan Pablo Isaza Denunciar

0

I understood. You should learn about array methods such as map, filter, reduce. Here you go...

const items = [{
              "id":"4",
              "name":"ProductA",
              "manufacturer":"BrandA",
              "quantity":1,
              "price":"25"
          },{
              "id":"1",
              "name":"ProductB",
              "manufacturer":"BrandB",
              "quantity":5,
              "price":"20"
          }];
          
const result = items.map((item) => `${item.name} x ${item.quantity}`);
console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think I understand the question to say that the input is an array of objects, each containing an array of items. The key is that a nested array requires a nested loop. So, we iterate the objects and their internal items (see the lines commented //outer loop and // inner loop below)

Also, half-guessing from the context, it looks like the that the OP aims to assemble a sort of invoice for each object. First a demo of that, (and see below for the version simplified to exactly what the OP asks)...

const addInvoice = obj => {
  let total = 0;
  // inner loop
  obj.invoice = obj.items.map(i => {
    let subtotal = i.quantity * i.price;
    total += subtotal
    return `name: ${i.name}, qty: ${i.quantity}, unit price: ${i.price}, subtotal: ${subtotal}`
  });
  obj.invoice.push(`invoice total: ${total}`);
}

const objects = [{
  "isLoaded": true,
  "items": [{
    "id": "4",
    "name": "ProductA",
    "manufacturer": "BrandA",
    "quantity": 1,
    "price": "25"
  }, {
    "id": "1",
    "name": "ProductB",
    "manufacturer": "BrandB",
    "quantity": 5,
    "price": "20"
  }],
  "coupons": null
}]

// outer loop
objects.forEach(addInvoice);
console.log(objects);

If my guess about the goal went to far, just remove the unit price, subtotal and total lines from the invoice function...

const objects = [{
  "isLoaded": true,
  "items": [{
    "id": "4",
    "name": "ProductA",
    "manufacturer": "BrandA",
    "quantity": 1,
    "price": "25"
  }, {
    "id": "1",
    "name": "ProductB",
    "manufacturer": "BrandB",
    "quantity": 5,
    "price": "20"
  }],
  "coupons": null
}]

const summaryString = obj => {
  return obj.items.map(i => `${i.name}, ${i.quantity}`);
}
const strings = objects.map(summaryString);
console.log(strings);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda