获得嵌套的obj值 [英] Getting nested obj value

查看:91
本文介绍了获得嵌套的obj值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下obj:

var inputMapping = {
 nonNestedItem: "someItem here",
 sections: {
   general: "Some general section information" 
 }
};

我正在写一个函数 get 通过传入字符串nonNestedItem或在嵌套情况下sections.general传递该数据。我不得不使用 eval 我想知道是否有更好的方法可以做到这一点。

I'm writing a function to get that data by passing in a string "nonNestedItem" or in the nested case "sections.general". I'm having to use an eval and I was wondering if there was maybe a better way to do this.

这是我到目前为止所做的工作还可以。但要改进!

Here is what I have so far and it works okay. But improve!

function getNode(name) {
  var n = name.split(".");

  if (n.length === 1) { 
   n = name[0];
  } else { 
    var isValid = true,
        evalStr = 'inputMapping';

    for (var i=0;i<n.length;i++) { 
      evalStr += '["'+ n[i] +'"]';

      if (eval(evalStr) === undefined) {
        isValid = false;
        break;
      }
    }

    if (isValid) { 
      // Do something like return the value 
    }
  }
}

Linky to Jsbin

推荐答案

您可以使用 Array.prototype.reduce 这样的函数

You can use Array.prototype.reduce function like this

var accessString = "sections.general";

console.log(accessString.split(".").reduce(function(previous, current) {
    return previous[current];
}, inputMapping));

输出

Some general section information

如果你的环境没有支持 reduce ,你可以使用这个递归版本

If your environment doesn't support reduce, you can use this recursive version

function getNestedItem(currentObject, listOfKeys) {
    if (listOfKeys.length === 0 || !currentObject) {
        return currentObject;
    }
    return getNestedItem(currentObject[listOfKeys[0]], listOfKeys.slice(1));
}
console.log(getNestedItem(inputMapping, "sections.general".split(".")));

这篇关于获得嵌套的obj值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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