Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda