V
V
vitaliyVH2019-09-03 13:42:50
JavaScript
vitaliyVH, 2019-09-03 13:42:50

How to convert from array to object by element count in JS?

Good afternoon!
There is an array

['data-name="SG 553 | Integrale"',
  'data-quality="Classified"',
  'data-minwear="0.00"',
  'data-maxwear="1.00"',
  'data-name="Dual Berettas | Twin Turbo"',
  'data-quality="Classified"',
  'data-minwear="0.00"',
  'data-maxwear="1.00"',
  'data-name="AK-47 | Safety Net"',
  'data-quality="Restricted"',
  'data-minwear="0.00"',
  'data-maxwear="0.60"']

How can I translate this array into an object, with such a structure
collection = {
    1: {
        Quality: {
            Classified: {
                'SG 553 | Integrale': 0.00-1.00,
                'Dual Berettas | Twin Turbo': 0.00-1.00,
            }
            Restricted: {
                'AK-47 | Safety Net': 0.00-0,60
}
        }
    }
}

Those. each first element of the array is the name of each, the 2nd is a certain quality, and 3 and 4 are the parameters of this name (1 element) There
are more collections, qualities too, therefore such an inconvenient object.
I've been scratching my head for 5 days how to translate this, please help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2019-09-03
@vitaliyVH

let collection = {1: {Quality: {}}};
for (let i = 0, l = data.length; i < l; i += 4) {
  const [name, quality, minwear, maxwear] = data.slice(i, i + 4).map((n) => n.match(/"(.*?)"/)[1]); 
  collection[1].Quality[quality] = collection[1].Quality[quality] || {}; 
  collection[1].Quality[quality][name] = `${minwear}-${maxwear}`;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question