Last active
May 31, 2019 08:22
-
-
Save shenqihui/5a5a9b8370f5c087ec9271d33fbf0d12 to your computer and use it in GitHub Desktop.
WXS 中遍历对象
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 文件名应该是 object_each.wxs , github 上没法识别,所以直接用 js 后缀,如果name 中含有 " 引号,那就洗洗睡吧,不适合这样的业务。 | |
// 匹配 key 的 regex | |
var keyRe = getRegExp('"[^"]+":', 'img'); | |
// 匹配 name 替换的 regex | |
var replaceRe = getRegExp('[":]', 'img'); | |
var objectEntries = function (target) { | |
var entries = []; | |
var targetString = JSON.stringify(target); | |
var targetStringMatch = targetString.match(keyRe); | |
if (targetStringMatch && targetStringMatch.length && targetStringMatch.forEach) { | |
targetStringMatch.forEach(function (match) { | |
var name = match.replace(replaceRe, ''); | |
var value = target[name]; | |
if (undefined !== value && undefined !== name) { | |
entries.push([name, value]); | |
} | |
}); | |
} | |
return entries; | |
} | |
var a = { | |
a: 1, | |
b: 2, | |
c: 3, | |
} | |
console.log(JSON.stringify(objectEntries(a))); | |
module.exports = objectEntries; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment