json.data
– массив объектов. Массив хочется свести к единственному значению (сумме) — значит, нужен reduce().then(json => {
// сумма полей price
const sum = json.data.reduce((acc, c) => acc + c.price, 0);
// ...
По-хорошему надо ещё проверять. что валюта у всех товаров одинакова ) Почему именно ноды, а не элементы или еще как-то?Node дословно переводится как узел.
- почему тут нодыNode - любой объект DOM, в нем реализованы базовые методы.
- а тут элемент?
В чем разница?
const KEY = 'myLSkey';
const ymd = date =>
new Date(date.setTime(date.getTime() - date.getTimezoneOffset() * 6e4))
.toISOString()
.substring(0, 10);
const today = ymd(new Date()); // '2022-06-23'
const data = {
date: today,
count: 1,
...JSON.parse(localStorage.getItem(KEY)),
};
if (data.date !== today) {
data.date = today;
data.count++;
}
localStorage.setItem(KEY, JSON.stringify(data));
function interval(arr, delay, callback) {
let index = -1;
return setInterval(() => {
index = (index + 1) % arr.length;
callback(arr[index]);
}, delay);
}
const intervalId = interval(keys, 1500, function(text) {
this.innerText = text;
}.bind(document.querySelector('.slide-words')));
Set
удобен, например, когда нужно оставить из набора данных только уникальные.const data = [ 1, 2, 2, 3, 3, 3 ];
const unique = [...new Set(data)];
unique // [ 1, 2, 3 ]
Map
хорош тем, что ключами в нём могут быть и объекты. Например, HTML-элементы, для которых захочется хранить какие-то данные. И Map запоминает порядок добавления элементов, что может быть полезно при переборе. arr.map((item) => ({ ...item, averagePrice: item.finance / item.physicalVolume }));
<script src="main.js"></srcipt> -> <script src="main.js?1234567890"></srcipt>
document.querySelectorAll('.count-wrapper').forEach((wrapper) => {
const minusButton = wrapper.querySelector('.count-minus');
const plusButton = wrapper.querySelector('.count-plus');
const counterElement = wrapper.querySelector('.counter');
if (!minusButton || !plusButton || !counterElement) {
return;
}
let counter = Number(counterElement.textContent.trim()) || 0;
minusButton.addEventListener('click', (event) => {
event.preventDefault();
if (counter > 0) {
counter--;
}
counterElement.textContent = counter;
});
plusButton.addEventListener('click', (event) => {
event.preventDefault();
counter++;
counterElement.textContent = counter;
});
});
const colors = {
'3': 'red',
'2': 'green',
'1': 'blue',
'0': 'black',
};
const setColor= input => {
const { value } = input;
if (colors.hasOwnProperty(value)) {
input.style.backgroundColor = colors[value];
}
}
const onInput = e => {
setColor(e.target);
}
document.querySelectorAll('input')
.forEach(elem => {
elem.addEventListener('input', onInput);
setColor(elem);
});
const makeTree = (root) => {
const tree = {};
const step = (root, branch) => {
root.querySelectorAll(':scope > [class^="block"]').forEach((element, index) => {
const className = [...element.classList.values()].find(
(className) => className.startsWith('block')
) ?? element.className;
const key = `${className}_${index + 1}`;
branch[key] = {};
const control = element.querySelector(':scope > input');
if (control) {
branch[key].value = control.value;
}
step(element, branch[key]);
});
};
step(root, tree);
return tree;
};
const tree = makeTree(document.body);
console.log(tree);
const makeTree = (root) => {
const tree = {};
const step = (root, branch) => {
root.querySelectorAll(':scope > [class^="block"]').forEach((element, index) => {
const className = [...element.classList.values()].find(
(className) => className.startsWith('block')
) ?? element.className;
const key = `${className}_${index + 1}`;
const controls = element.querySelectorAll(':scope > input');
branch[key] = {
values: [...controls].reduce((acc, control) => {
if (control.id) {
acc[control.id] = control.value;
}
return acc;
}, {})
};
step(element, branch[key]);
});
};
step(root, tree);
return tree;
};
const tree = makeTree(document.body);
console.log(tree);