美文网首页
js获取深层次属性

js获取深层次属性

作者: YellowPoint | 来源:发表于2020-01-17 11:43 被阅读0次

方式一:通过递归

// 获取js深层次属性兼容有[]的情况
function getJsonValue(obj, node) {
 if (!obj) {
   return null;
 }
 if (!node) {
   return null;
 }
 let nodes = node.split(".");
 let item = nodes[0]
 let newObj = obj[item]
 if (nodes[0].indexOf('[') > -1) {
   let itemArr = item.split("[")
   newObj = obj[itemArr[0]]
   newObj = newObj[itemArr[1].slice(0, -1)]
 }
 if (nodes.length == 1) {
   return newObj;
 }
 return getJsonValue(newObj, node.substring(item.length + 1));
}
var a = {
 aa: {
   aaa: [1, 2, 3]
 }
}

console.log(getJsonValue(a, 'aa.aaa[1]'))

参考下面文章后js获取深层次属性,一道很经典的面试题,在此基础上通过替换[]为.来兼容有[]的情况

ES7可选链式调用 console.log(data.user?.address?.street) //undefined

方式二:reduce

String.prototype.replaceAll = function (search, replacement) {
  var target = this;
  search = escapeRegExp(search)
  return target.replace(new RegExp(search, 'g'), replacement);
};
// 兼容正则中需要转义的
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
const safeGet = (o, path) => {
  // 只要把[]都替换了就好了嘛
  path = path.replaceAll('[', '.')
  path = path.replaceAll(']', '')
  console.log('path', path)
  try {
    return path.split('.').reduce((o, k) => o[k], o)
  } catch (e) {
    return void 666
  }
}

var a = {
  aa: {
    aaa: [1, 2, 3]
  }
}

console.log(safeGet(a, 'aa.aaa[1]'))

相关文章

  • js获取深层次属性

    方式一:通过递归 参考下面文章后js获取深层次属性,一道很经典的面试题,在此基础上通过替换[]为.来兼容有[]的情...

  • 原生JS中DOM元素的操作

    获取dom 修改属性 .获取对象的属性 .js获取非行内样式属性 innerHTML dom 属性设置与获取 Do...

  • AppleScript-record对象

    理解类似于OC中的字典,js中的对象 创建 获取属性the 属性名 of 对象 设置属性 获取属性数量

  • js 获取属性

    1. 使用“ . ”来访问对象属性 语法: objectName.propertyName 其中,objectNa...

  • OC与JS交互

    ios与js交互,获取webview完整url,title,获取元素并赋值跳转 JS 对象document:属性d...

  • JS DOM编程艺术第6/7两章-完整code

    知识点 获取节点 获取属性 完整代码 html文档 css部分 js部分

  • video标签属性方法和事件

    标签的属性 html 代码: //audio和video都可以通过JS获取对象,JS通过id获取video和aud...

  • 连字符表示法和驼峰表示法的转换

    在JS中获取CSS属性,我们会使用计算属性 getComputedStyle() window.getComput...

  • DOM节点

    DOM节点 js获取元素及其属性 1.访问或获取节点 getElementById(); getElementsB...

  • js获取元素属性

    获取元素的属性分为两种类型: 1-获取元素常见的属性(class,id,type,value……) 2-获取自定义...

网友评论

      本文标题:js获取深层次属性

      本文链接:https://www.haomeiwen.com/subject/hkeczctx.html