Home > Mobile >  How to convert attribs to object in javascript
How to convert attribs to object in javascript

Time:10-31

I am struggling to convert these html attributes I extracted from widget tag to an object so I can change some of its values. Following are the attributes.

widget="fixtures" competition="1" season="2020" match="123" template="cell" live="true" sport="hockey"

What I have tried is JSON.stringify and JSON.parse but nothing seems to be working.

This is what I have done, the ending result seems like object but when I try to access one of any key from it I get undefined.

htmlAttribs = htmlAttribs.replace(/[=]/g, ':');
htmlAttribs = htmlAttribs.replace(/[ ]/g, ', ');
htmlAttribs = `{${htmlAttribs}}`;
htmlAttribs = JSON.stringify(htmlAttribs);
    
htmlAttribs = JSON.parse(htmlAttribs);
console.log(htmlAttribs);

CodePudding user response:

This worked for me.

htmlAttribs = htmlAttribs.replace(/[=]/g, ':');
htmlAttribs = htmlAttribs.replace(/[ ]/g, ', ');

const obj = eval('({'   htmlAttribs   '})');

One can access values using object.key_name

CodePudding user response:

I would split each of the attributes on an empty space ' ' then use reduce to build up an object setting each property and value.

const htmlAttribs = `widget="fixtures" competition="1" season="2020" match="123" template="cell" live="true" sport="hockey"`;

const attribs = htmlAttribs
  .split(' ')
  .reduce((prev, curr) => {
    const [key, value] = curr.split('=');
    prev[key] = value.replaceAll('"', '');
    return prev;
  }, {});
  
console.log(attribs);

Results in an object looking like:

{
  "widget": "fixtures",
  "competition": "1",
  "season": "2020",
  "match": "123",
  "template": "cell",
  "live": "true",
  "sport": "hockey"
}
  • Related