javascript - 将一个对象分成更小的对象
问题描述
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"
}}]
如果可能的话,我希望你能帮我解决这个问题提前谢谢:)
解决方案
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"
}
}
]
推荐阅读
- r - 如何折叠/减少因子水平的数量
- python - Tensorflow:在函数内填充张量
- c# - 基于另一个属性值的属性上的自定义 JsonConverter
- python - 无法从带有漂亮汤的“a”标签中提取 href 属性
- javascript - 将npm包导入客户端javascript
- android - 当我在 Android Studio 中编辑应用程序代码时,我看到了这段代码
- php - PHP:mcrypt & openssl 产生不同的输出
- jquery - 更改所选分组单选按钮的背景
- angular - Angular2+ 将所有组件 css/scss 捆绑到一个文件中
- jquery - IE11 window.scroll 出现问题...但又不是