I have an array of HTML div elements with a data-param-name
attribute which may duplicate elements that exist in the array. now I want to bind object values to that inner HTML of the elements.
For example:
data: {
user: [
{name: 'saeed', job: ['engineer']},
{name: 'ali', job: ['employee']}
],
type: 'x'
}
And array of html attribute is:
[
<div data-param-name="data.user.name"></div>, //inner html should be: 'saeed'
<div data-param-name="data.type"></div>, //inner html should be: 'x'
<div data-param-name="data.user.name"></div>, //inner html should be: 'ali'
<div data-param-name="data.user.job"></div>, //inner html should be: 'engineer'
]
I wrote this code but it did not work as expected:
for (const element of elementCollection) {
const dataTitle = element.getAttribute('data-title');
const dataParamName = element.getAttribute('data-param-name');
if (dataParamName) {
const splitArray = dataParamName.toLowerCase().split('.');
const result = splitArray.reduce((acc: any, cur: any) => {
if (Array.isArray(acc)) {
return acc[arr[dataParamName]]?.[cur];
}
return acc?.[cur] || '';
}, fields);
if (result) {
if (typeof result === 'number') {
element.innerHTML = `${zeroSeparator(result)}`;
} else {
element.innerHTML = result ? toPersianDigit(result) : '';
}
}
}
}
I will appreciate for helping me!