const FILTER_VALUE = 'eg';
const filteredArr = arr.reduce((acc, el) => {
const items = el.items
.filter(n => n.keywords.some(m => m.includes(FILTER_VALUE)))
.map(n => ({ ...n, keywords: [...n.keywords] }));
if (items.length) {
acc.push({ ...el, items });
}
return acc;
}, []);
const $initial = $('.some-div').clone();
$('.some-div').replaceWith($initial);
$('.some-div').replaceWith($initial.clone());
const find = (arr, id) =>
(Array.isArray(arr) ? arr : []).reduce((found, n) =>
found || (n.id === id ? n : find(n.children, id))
, null);
selected() {
return this.active.length
? find(this.users, this.active[0])
: null;
},
return-object
- тогда в active вместо ключей будут объекты. Соответственно, искать ничего не надо, вычисляемое свойство сократится доselected() {
return this.active[0];
},
const queryIfSelector = f => x =>
f(typeof x === 'string' ? document.querySelector(x) : x);
const getTableData = queryIfSelector(table =>
Array.from(table.querySelectorAll('tbody tr'), tr =>
Object.fromEntries(Array.from(tr.querySelectorAll('td'), td => [
td.getAttribute('data-name'),
td.querySelector('input').value,
]))
)
);
// или
const getTableData = queryIfSelector(table =>
Array.prototype.flatMap.call(table.tBodies, tbody =>
Array.prototype.map.call(tbody.rows, tr =>
Array.prototype.reduce.call(tr.cells, (acc, td) => (
acc[td.dataset.name] = td.firstElementChild.value,
acc
), {})
)
)
);
// или
const getTableData = queryIfSelector(table => {
const result = [];
const numHeadRows = table.querySelectorAll('thead tr').length;
for (const input of table.querySelectorAll('tbody input')) {
const td = input.closest('td');
const i = td.parentNode.rowIndex - numHeadRows;
const item = result[i] = result[i] || {};
item[td.attributes['data-name'].value] = input.value;
}
return result;
});
const data1 = getTableData('#table1');
const data2 = getTableData(document.querySelector('#table2'));
const Component = Vue.extend(...);
document.body.appendChild(new Component(...).$mount().$el);
for (name, items) in cook_book:
print('\n%s:' % name.capitalize())
for (ingredient, quantity, unit) in items:
print('%s, %d %s' % (ingredient, quantity * person, unit))
document.querySelector('textarea').addEventListener('keydown', e => e.preventDefault());
<textarea readonly></textarea>
$('table tr').get().reduce((acc, n) => acc.then(() => $.ajax(...)), $.Deferred().resolve());
<select v-model="selected">
<option v-for="item in options" :value="item.value">
{{ item.title }}
</option>
</select>
data: () => ({
selected: null,
...
}),
computed: {
monthRate() {
if (this.selected === 'year') {
return this.percent / 12 / 100;
} else if (this.selected === 'month') {
return this.percent / 100;
} else {
return 0;
}
},
},
нужно, чтобы в зависимости от выбранной опции, функция срабатывала по разной формуле
monthRate() {
return this.percent * this.selected / 100;
},
const text = '|||';
.$el.children().slice(1).before(text);
// или
$el.children(':nth-child(n + 2)').before(text);
// или
$el.find('> :nth-last-child(n + 2)').after(text);
Array.prototype.forEach.call(
el.children,
(n, i) => i && n.before(new Text(text))
);
// или
for (const n of el.children) {
if (n.nextElementSibling) {
n.insertAdjacentText('afterend', text);
}
}
// или
for (let i = 1; i < el.children.length; i++) {
el.insertBefore(document.createTextNode(text), el.children[i]);
}
// или
el.querySelectorAll(':scope > * + *').forEach(n => n.outerHTML = text + n.outerHTML);
const gallerySelector = '.js-product__item';
const previewSelector = '.view__item img';
const mainImageSelector = '.js-product__img--current';
const showImage = preview => preview
.closest(gallerySelector)
.querySelector(mainImageSelector)
.src = preview.src;
document.addEventListener('click', ({ target: t }) => {
if (t.matches(previewSelector)) {
showImage(t);
}
});
// или
document.querySelectorAll(previewSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => showImage(e.target));
const keys = [
[
{ on: [ 'ё', 'Ё' ], off: [ '`', '~' ], name: 'Backquote' },
{ on: [ '1', '!' ], off: [ '1', '!' ], name: 'Digit1' },
...
],
...
];
document.querySelector('.keyboard').innerHTML = keys.map(row => `
<div class="row">${row.map(n => `
<div class="key">
<span class="${n.name} on">
<span class="case down">${n.on[0]}</span>
<span class="case up">${n.on[1]}</span>
</span>
<span class="${n.name} off">
<span class="case down">${n.off[0]}</span>
<span class="case up">${n.off[1]}</span>
</span>
</div>`).join('')}
</div>`).join('');
data-id={user.id}
const elemId = +e.currentTarget.dataset.id;