如何分别遍历多层对象中的元素的值?

12style
  • 38

存储在油猴子中的数组,如何分别遍历到cfg对象中,
"text"的"3"中"arg"的第1个、第2个、第3个值
"link"的"3"中"arg"的第1个、第2个值
"image"的"2"中"arg"的第1个、第2个值
"image"的"4"中"arg"的第1个、第2个、第3个值

目的,为了将存储的值使用sel()和前台界面的select选框的值对比,设置option元素中的selected属性,作为选框默认值

原脚本地址https://greasyfork.org/zh-CN/...
通过GM_listValues()获取存储的所有key,除了cfg对象,还有其他对象,只需要cfg中的对应值
// @grant GM_listValues

let allValue = GM_listValues();
allValue.forEach(function(value, index) {

}
"搜索图片": {
        "name": "搜索图片",
        "times": 7,
        "date": "2021/05/18 21:34:55"
    },
"新标签打开图片(img)": {
        "name": "新标签打开图片(img)",
        "times": 9,
        "date": "2021/05/18 21:30:37"
    },
"cfg": {
        "Gesture": {
            "mouseButton": 2,
            "Timeout": {
                "active": true,
                "duration": 1
            }
        },
        "Hinter": {
            "background": "",
            "funNotDefine": null
        },
        "Drag": {
            "linktextAslink": true,
            "dragInTextarea": true
        },
        "directions": 8,
        "language": "zh",
        "gesture": {},
        "text": {
            "1": {
                "name": "pasteText",
                "arg": [],
                "alias": "粘贴"
            },
            "2": {
                "name": "space",
                "arg": [],
                "alias": "空格"
            },
            "3": {
                "name": "searchText",
                "arg": [
                    "https://www.bing.com/search?q=",
                    "false",
                    "true"
                ],
                "alias": "搜索"
            }
        },
        "link": {
            "1": {
                "name": "copyLinkText",
                "arg": []
            },
            "3": {
                "name": "openLink",
                "arg": [
                    false,
                    true
                ]
            },
            "9": {
                "name": "copyLink",
                "arg": []
            }
        },
        "image": {
            "1": {
                "name": "copyImgURL",
                "arg": []
            },
            "2": {
                "name": "openImgURL",
                "arg": [
                    false,
                    true
                ]
            },
            "4": {
                "name": "searchImg",
                "arg": [
                    "https://www.tineye.com/search?url=U-R-L",
                    false,
                    true
                ]
            },
            "8": {
                "name": "openImgLink",
                "arg": [
                    false,
                    true
                ]
            }
        }
    }

下拉选框内容

options = {
                imgSearchEnging: {// image searching
                    TinEye:  "https://www.tineye.com/search?url=U-R-L",
                    Yandex:  "https://yandex.com/images/search?rpt=imageview&url=U-R-L"
                },
                searchEnging: {// text searching
                    Baidu:   "https://www.baidu.com/s?wd=",
                    Google:  "https://www.google.com/search?q="
                },
                foreGround: {
                    前台:    "ture",
                    后台:    "false"
                }
            };

下拉选框html

            html += `<span>${name}</span><span name="alias">${argu.alias ? argu.alias : local[type][name][cfg.language]}</span><b style="visibility:${argu.arg.length ? "visible" : "hidden"};" name="toggleArgument">▲</b><input type="text" name="${name}" value="${trackTxt}" data-mark="${type}" readonly="readonly"><br/><div class="fnArgument">`;
            if(argu.arg.length > 0){
                argValue = trackTxt ? argu.arg : [];
                agrDetail = fnLocal.arg[name].arg;
                description = fnLocal.arg[name].description[cfg.language];

                for(i in agrDetail){
                    rand = Math.floor(Math.random()*1000);
                    switch (agrDetail[i].slice(0,5)) {
                        case 'selec':
                            selectName = agrDetail[i].split(':').pop();
                            html += `<span><input type="text" value=${argValue[i] || ''}><select name="fnSelect">`;
                            for (let k in options[selectName]){

                                html += `<option value=${options[selectName][k]} ${sel(cfg.language, options[selectName][k])}>${k}</option>`;
                            }
                            html += '</select></span>';
                            break;
                        default:
                            html = `<span style="visibility:hidden;"></span>`;
                            break;
                    }
                }
            }
            return html + "</div>";

对比函数

        function sel(val1, val2){
            return val1 == val2 ? 'selected="selected"' : '';
        }
回复
阅读 494
1 个回答

可以提供相关属性的visitor,然后更具他的值,字段名,上级节点在对其做相应的逻辑

const isPlainObject = (obj) => {
  return typeof obj === "object" && obj !== null;
};

const defineProp = (obj, key, val) => {
  Object.defineProperty(obj, key, {
    value: val,
    configurable: true,
    enumerable: false
  });
};

const traverse = (root, visitor) => {
  const dfs = (vertex, origin, name) => {
    if (!vertex) return;

    if (
      Array.isArray(vertex) ||
      typeof vertex === "string" ||
      typeof vertex === "number"
    ) {
      visitor[name] && visitor[name](origin, name, vertex);
      return;
    }

    for (const key of Object.keys(vertex)) {
      if (isPlainObject(vertex[key])) defineProp(vertex[key], "parent", vertex);

      dfs(vertex[key], vertex, key);
    }
  };

  dfs(root, null, "");
};

traverse(temp, {
  arg(parentNode, name, vertex) {
    console.log(parentNode, name, vertex);
  }
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏