0

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!

Saeed Hemmati
  • 453
  • 2
  • 11
  • This would be easier if `data-param-name` can be a function: `data-param-name={data => data.user.name}` (which I guess you'd need to handle with your own component using props). Is that an option? Otherwise, you can use something like: [Accessing nested JavaScript objects and arrays by string path](https://stackoverflow.com/a/6491621) – Nick Parsons Aug 12 '23 at 05:21
  • @NickParsons It has limitation in its value. the values just be like something I wrote and the main challenge is it. I think which I should get data-param-names and map the values to like something 'data.user.0.name' – Saeed Hemmati Aug 12 '23 at 05:23

0 Answers0