簡體   English   中英

將 object 分成更小的對象

[英]Separate an object into smaller objects

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();
})();

output是這樣的:

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

我想將樣式 output 分成對象,如下所示

我對此進行了一些研究,但找不到任何有用的東西

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

}}]

如果可能的話,我希望你能幫我解決這個問題提前謝謝:)

讓我們試試這個:

let s = "visibility: visible; width: 100%; margin-left: 0px; height: 301.538px; margin-top: -3.26923px; position: absolute;"

let res = Object.fromEntries(s.split(';').map(item => item.split(':').map(subitem => subitem.trim())))

 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"
    }
  }
]

對於您擁有的數據類型,這將起作用:

Object.fromEntries(style.split('; ').map( item => item.split(': ')))

測試:

const style = "visibility: visible; width: 100%; margin-left: 0px; height: 301.538px; margin-top: -3.26923px; position: absolute;"
const styleObj = Object.fromEntries(style.split('; ').map( item => item.split(': ')));
// use styleObj

結果: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM