S
S
Speakea1y12892019-07-04 12:11:27
JavaScript
Speakea1y1289, 2019-07-04 12:11:27

How to parse product features in div blocks and create a JavaScript array from them?

Good afternoon. There is a site with a product, for example - https://www.xcom-shop.ru/hp_22-c0015ur_645720.html
There is a code that I paste into the Google Chrome console and execute on this site:

$('.prop-line').each(function(index, element) {
  if (!$(element).hasClass('prop-line-wide')) {
    var xcom_prop_name = $(element).find('.call').text();
    var xcom_prop_value = $.trim($(element).find('.prop-value').text());
    var xcom_prop_group = $.trim($(element).find('h3').text());
    
    if ($.trim($(element).find('h3').text()) == "") {
      console.log("TITLE_PROP: " + xcom_prop_name, "PROP_VALUE: " + xcom_prop_value);
    } else {
      console.log("GROUP_PROPS: " + xcom_prop_group);
    }
  }
});


When executing this code. All product characteristics are parsed and output to the console: GROUP_PROPS - name of a specific group of characteristics; TITLE_PROP - name of a feature from the character group; PROP_VALUE - characteristic value.
b80503453b.png

The task is the following - to wrap all the characteristics in an array with the following structure:
array(
  [GROUP_PROPS] => array(
    "НАЗВАНИЕ_ГРУППЫ_ХАР-ОК_1" =>
    array(
      [НАЗВАНИЕ_ХАР-КИ_1] => "ЗНАЧЕНИЕ_ХАР-КИ_1",			
      [НАЗВАНИЕ_ХАР-КИ_2] => "ЗНАЧЕНИЕ_ХАР-КИ_2",			
      [НАЗВАНИЕ_ХАР-КИ_3] => "ЗНАЧЕНИЕ_ХАР-КИ_3",			
      ...
    ),
    "НАЗВАНИЕ_ГРУППЫ_ХАР-ОК_2" =>
    array(
      [НАЗВАНИЕ_ХАР-КИ_1] => "ЗНАЧЕНИЕ_ХАР-КИ_1",			
      [НАЗВАНИЕ_ХАР-КИ_2] => "ЗНАЧЕНИЕ_ХАР-КИ_2",			
      [НАЗВАНИЕ_ХАР-КИ_3] => "ЗНАЧЕНИЕ_ХАР-КИ_3",			
      ...
    ),
    ...
  ),
);

GROUP_NAME_CHAR-OK_* - value from GROUP_PROPS; TITLE_CHARACTERISTICS_* - value from TITLE_PROP; CHARACTERISTICS_VALUE_* - value from PROP_VALUE;

How can I do that?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Speakea1y1289, 2019-07-04
@Speakea1y1289

Here is the solution:

let arr = {};
$('#prop-columns .prop-line.delimiter').each(function () {
    const category = $(this);
    let props = {};
    category.nextUntil('.delimiter').each(function() {
        const item = $(this);
        props[item.find('.call').text()] = item.find('.prop-value').text();
    });
    arr[category.text()] = props;
});
console.log(arr);

V
Vladislav Polyakov, 2019-07-04
@polRk

Create a Map object, new Map(string, Array). Where the key will be the name of the group, and the value will be an array of objects {key: value}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question