使用字符串路径访问JSON数据? [英] Access JSON data with string path?

查看:64
本文介绍了使用字符串路径访问JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var give = 'i.want.it';

var obj = {
    i: {
        want: {
            it: 'Oh I know you do...'
        }
    }
};

console.log(obj[give]); // 'Oh I know you do...'

我可以使用某种路径字符串以某种方式获取对象字符串吗?我正在尝试将关系存储在自己的文档中不能存在的数据库中.

Can I somehow get the object string using a path String of some sort? I'm trying to store a relationship in a database where the field it can't be in it's own document.

推荐答案

使用

var give = 'i.want.it';

var obj = {
  i: {
    want: {
      it: 'Oh I know you do...'
    }
  }
};


var res = give.split('.').reduce(function(o, k) {
  return o && o[k];
}, obj);

console.log(res);

这篇关于使用字符串路径访问JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆