Search code examples
javascriptloopsobjectnestedangular7

How to access the property of objects obtained after a forEach?


I receive from the backend an array of nested objects, I go through them to modify values and filter according to conditions I need for my application

      const data = this.market;
      data.forEach(function(item: any, i) {
        if (item.functional_id === 'cool') {
          data.splice(i, 1);
          data.unshift(item);
        }
        if (item.functional_id === 'max') {
          item.name = 'Max min';
        }
        item.products.forEach(function(product) {
          product.items.forEach(function(article) {
            console.log(article);
          });

        });
      });
  }


at the console.log point I receive several objects with the structure of the following

{
  "name": "Standard",
  "description": "for 50",
  "price": 20,
  "functional_id": "sacs_housse"
}

some of the items I get have a price with a decimal point, separated by a dot and I want to check that it has that dot to replace it with a comma. so I've tried to put a condition on replacing the points. But I don't see a way to access the property since all the type of loop I've tried returns an error. some of the things I've tried like the following.

const data = this.market;
      data.forEach(function(item: any, i) {
        if (item.functional_id === 'cool') {
          data.splice(i, 1);
          data.unshift(item);
        }
        if (item.functional_id === 'furniture') {
          item.name = 'Max min';
        }
        item.products.forEach(function(product) {
          product.items.forEach(function(article) {
            const price = item.price;
            if (price.contains('.')) {
              price.replace(/./g, ',');
            }            
          });

        });
      });

someone who sees the mistake I'm making and can help me out. Thank you in advance.


Solution

  • I found this method in mdn that works perfectly, thanks for everyone's help

    new Intl.NumberFormat('de-DE').format(item.price);
    

    Here's the link to mdn https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat