Home > Enterprise >  Nested array issue in JavaScript
Nested array issue in JavaScript

Time:01-22

I use localForage to get offline stored data.

localforage.iterate(function(value, key, iterationNumber) {

console.log([key, value]);  });

I am getting an 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 load all Product names from the array and their quantity.

For example:

ProductA x 1

ProductB x 5

const result = [key, value].map((item) => `${item.name} x ${item.quantity}`);

This is not working.

Array [ "undefined x undefined", "undefined x undefined" ]

CodePudding user response:

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);

CodePudding user response:

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]);
  console.log(value.items.map(it => `${it.name} x ${it.quantity}`));
});

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());

CodePudding user response:

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);

  •  Tags:  
  • Related