succesItem='succesItem'
Vue.options.filters
. Соответственно:const filteredValue = Vue.options.filters.someFilter(value);
// или, если вспомнить, что компоненты являются экземплярами Vue
const filteredValue = this.constructor.options.filters.someFilter(value);
function setNestedVal(root, path, val) {
const keys = path.split('.');
const key = keys.pop();
keys.reduce((acc, n) => acc[n] ??= {}, root)[key] = val;
}
setNestedVal(data, '0.arr.0.str', 'hello, world!!');
setNestedVal(data, '0.arr.1.num', 666);
Интересуют готовые решения
Нужно изменить этот массив, преобразовав все строки с датами в нём, независимо от того, как глубоко они вложены, в объекты.
const replaceValues = (data, test, transform) =>
test(data)
? transform(data)
: data instanceof Array
? data.map(n => replaceValues(n, test, transform))
: data instanceof Object
? Object.fromEntries(Object
.entries(data)
.map(([ k, v ]) => [ k, replaceValues(v, test, transform) ])
)
: data;
const newData = replaceValues(
data,
x => typeof x === 'string' && /^\d{2}\.\d{2}\.\d{4}$/.test(x),
str => new Date(str.split('.').reverse().join('-'))
);
const sum = arr.reduce((acc, n) => acc + n.number, 0);
const newArr = arr.map(n => ({ ...n, percent: n.number / sum * 100 }));
Object
.entries(arr.reduce((acc, n) => (
n = n.match(/('.*?'):'(.*?)'/),
(acc[n[1]] ??= []).push(n[2]),
acc
), {}))
.map(n => `${n[0]}:'${n[1].join('|')}'`)
<vue-slick-carousel
ref="slick"
@hook:mounted="$refs.slick.$el.dataset.id = 666"
...
v-for
, значит вместо одной ссылки на экземпляр, будет массив. Надо индекс указывать. Ну и не забывать о том, что соответствие порядка элементов в массиве ссылок на экземпляры порядку элементов в массиве с данными не гарантируется.$letter = 'М';
$i = 0;
foreach (explode(', ', implode(', ', $products)) as $product) {
if (strpos($product, $letter) === 0) {
echo (++$i).") $product\n";
}
}
echo implode("\n", array_map(fn($n) => "$n[0] $n[2]", array_filter($arr, fn($n) => $n[1])));
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.3.4/cdn.min.js"></script>
<div x-data="{
items: [
{ id: 69, text: 'hello, world!!' },
{ id: 187, text: 'fuck the world' },
{ id: 666, text: 'fuck everything' },
],
}">
<template x-for="(n, i) in items">
<div>
<span x-text="n.text"></span>
<button @click="items.splice(i, 1)">x</button>
</div>
</template>
</div>
Код, который работает некорректно...
Object.freeze
назначить новое свойство уже не получится. Можно записать итератор в прототип массива (ну и после того, как он отработает, вернуть оригинальный итератор на место):const originalIterator = Array.prototype[Symbol.iterator];
Array.prototype[Symbol.iterator] = function() {
let i = -1;
return {
next: () => (i += 2) < arr.length
? { done: false, value: this[i] }
: { done: true },
};
};
setTimeout(() => Array.prototype[Symbol.iterator] = originalIterator, 0);
<div className="todoListMain"> <div className="header">
.todoListMain.header input {
.todoListMain
и .header
куда потерялся? Ну и с остальными стилями косяк тот же. const result = arr.flat();
// или
const result = Array.prototype.concat.apply([], arr);
// или
const result = arr.reduce((acc, n) => (acc.push(...n), acc), []);
// или
const result = [];
for (const n of arr) {
for (const m of n) {
result[result.length] = m;
}
}
seachCityName - обычная строка
seachCityName.value
. document.querySelectorAll('.filter__item').forEach(n => {
n.style.display = Array
.from(n.querySelectorAll('.filter__checkgroup-count'))
.some(m => +m.innerText.trim())
? 'block'
: 'none';
});
.hidden {
display: none;
}
for (const n of document.getElementsByClassName('filter__item')) {
n.classList.toggle('hidden', Array.prototype.every.call(
n.getElementsByClassName('filter__checkgroup-count'),
m => Number(m.textContent.trim()) === 0
));
}
function isEqual(a, b) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(n => a[n] === b[n]);
}
const result = arr1.concat(arr2.filter(n => arr1.every(m => !isEqual(n, m))));
const unique = function(arr, keys = n => n) {
const picked = new Map;
return arr.filter((...args) => {
const p = []
.concat(keys(...args))
.reduce((acc, k) => acc.set(k, acc.get(k) ?? new Map).get(k), picked);
return !p.set(this, p.has(this)).get(this);
});
}.bind(Symbol());
const result = unique([ ...arr1, ...arr2 ], n => [ n.teamId, n.userId ]);