How to format an array for JSON output?

Asked

Viewed 114 times

3

I have the following array:

const products = ["camisa-PP", "camisa-M", "camisa-G", "camisa-GG", "camisa-GG", "camiseta-PP", "camiseta-G", "cueca-M", "blusa-XG", "blusa-XG", "blusa-XG", "blusa-P"];

console.log(products)

And I need to convert it to JSON output like this:

{ 
  "camisa": { 
    "PP": 1, 
    "M": 1, 
    "G": 1, 
    "GG": 2 
  }, 
  "camiseta": { 
    "PP": 1, 
    "G": 1 
  }, 
  "cueca": { 
    "M": 1 
  }, 
  "blusa": { 
    "XG": 3, 
    "P": 1 
  }
}

I need each element to group the sizes of each product and the quantity. How to do this?

So far I’ve only been able to separate the values from the array it contained - and turned it into an object, but I have no idea how to proceed, follow the code below:

const products = ["camisa-PP", "camisa-M", "camisa-G", "camisa-GG", "camisa-GG", "camiseta-PP", "camiseta-G", "cueca-M", "blusa-XG", "blusa-XG", "blusa-XG", "blusa-P"];

let json = products.map(elements => JSON.parse(`{"${elements.split('-').join('":"')}"}`));

console.log(json);

1 answer

2


It should be mentioned first of all that there is no need to use JSON.parse there (assembling the JSON string in a literal way), since this is a less performatic medium and more susceptible to possible errors. Instead, you can use the language itself to manipulate data structures directly, without the need to create JSON strings.

In view of this, it must be understood that the expected result is an object and the input, an array. Thus, you need to think of a way to, from an initial empty object, increment the values as you traverse the array. An example of implementation would be this:

function groupProducts(arr) {
  // Nosso objeto (vazio) inicial:
  const result = {};
  
  for (const item of arr) {
    // Cada `item` é algo como "camisa-PP".
    // Portanto, podemos utilizar o método `split` para separá-lo em nome e tamanho:
    const [name, size] = item.split('-');
    
    // No caso do `name` da iteração atual ainda não ter sido criado:
    if (!result[name]) {
      result[name] = {};
    }
    
    result[name][size] = (result[name][size] || 0) + 1;
  }
  
  return result;
}

console.log(
  groupProducts([
    "camisa-PP", "camisa-M", "camisa-G",
    "camisa-GG", "camisa-GG", "camiseta-PP",
    "camiseta-G", "cueca-M", "blusa-XG",
    "blusa-XG", "blusa-XG", "blusa-P"
  ])
);

Basically, each element of the original array is always a string like "camisa-PP". Separating it by the hyphen (-), we get the product name and its size. This is done in each iteration of the loop.

In possession of this information, we create an object for each product and a sub object for each size. We use the operator ||, there doing short-circuit evaluation, to create the default zero initial value, in case the size has not yet been accounted for.

If you don’t understand any of the above code, take a step back and understand how to work with Javascript objects. Emphasize your studies from the beginning before trying to do something like this, which requires a certain mastery of language and its mechanisms.


There are also other ways to do this. Using Array.prototype.reduce, for example, it is another idea, but in the background the logic will always be the same.

  • 1

    Thank you very much Luiz, in fact I’m new in language, I even had an idea of how to solve but I didn’t know how to use the language tools. I was able to understand the code perfectly, thank you also for the explanation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.