Jozef Pintér
Jozef Pintér

Reputation: 44

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

Upvotes: 0

Views: 164

Answers (3)

jsN00b
jsN00b

Reputation: 3691

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

Upvotes: 1

danh
danh

Reputation: 62686

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

Upvotes: 0

Sivakumar A
Sivakumar A

Reputation: 701

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

Upvotes: 0

Related Questions