首页 > 解决方案 > 将一个对象分成更小的对象

问题描述

const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const options = ["iframe"]
const url = 'https://www.loungeincomfort.com.au/'
const page = await browser.newPage();
await page.goto(url);
for (var i = 0; i < options.length; i++) {
    const frame = await page.$$eval(options[i], e => e.map(a => {
        const attrs = a.getAttributeNames();
        const len = attrs.length;
        const test = {};
        for (var i = 0; i < len; i++) {
            //test[attrs[i]].push({ label: "Hello World" })
            test[attrs[i]] = a.getAttribute(attrs[i])
        }
        return test;
    }))
    console.log(frame);
}
await browser.close();
})();

输出是这样的:

[{
    "width": "1170",
    "height": "490",
    "style": "visibility: visible; width: 100%; margin-left: 0px; height: 301.538px; margin-top: -3.26923px; position: absolute;"
}]

我想将样式输出分成对象,如下所示

我对此进行了一些研究,但找不到任何有用的东西

[{
    "width": "1170",
    "height": "490",
    "style": {
           "visibility": "visible",
           "width": "100%",
           "margin-left": "0px",
           "height": "301.538px",
           "margin-top": "-3.26923px",
            "position": "absolute"

}}]

如果可能的话,我希望你能帮我解决这个问题提前谢谢:)

标签: javascriptnode.jsjsonobjectpuppeteer

解决方案


data = [{
  "width": "1170",
  "height": "490",
  "style": "visibility: visible; width: 100%; margin-left: 0px; height: 301.538px; margin-top: -3.26923px; position: absolute;"
}];
//console.log(data);
data.map(
  (item) => {
  // use a tmp variable to replace the style 
  const tmp = item.style;
  item.style={};
  tmp
  // split the style string into an array
  .split(';')
  // split individual items into keyvalue array
  .map((keyvalue) => keyvalue.split(':')
  // trim key and value
  .map(item=>item.trim()))
  // remove invalid values
  .filter((keyvalue)=>keyvalue.length===2)
  // assign to style
  .map((keyvalue)=>{item.style[keyvalue[0]]=keyvalue[1]})
  return item;
  }
)
console.log(data)

结果

[
  {
    "width": "1170",
    "height": "490",
    "style": {
      "visibility": "visible",
      "width": "100%",
      "margin-left": "0px",
      "height": "301.538px",
      "margin-top": "-3.26923px",
      "position": "absolute"
    }
  }
]

推荐阅读