Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现parse取值函数 #249

Open
wuxianqiang opened this issue Mar 14, 2020 · 0 comments
Open

实现parse取值函数 #249

wuxianqiang opened this issue Mar 14, 2020 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

wuxianqiang commented Mar 14, 2020

let obj = {
  a: 1,
  b: { c: 2 },
  d: [1, 2, 3, 4],
  e: [{ f: [5, 6] }]
}

let r1 = parse(obj, 'a')
let r2 = parse(obj, 'b.c')
let r3 = parse(obj, 'd[2]')
let r4 = parse(obj, 'e[0].f[0]')

实现方案1new Function

function parse(obj, str) {
  let fn = new Function('obj', 'return obj.' + str)
  return fn(obj)
}

实现方案2split

function parse(obj, str) {
  str = str.replace(/\[(\d+)\]/g, '.$1')
  let arr = str.split('.')
  arr.forEach(item => {
    obj = obj[item]
  })
  return obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant