开发者

split '{a}{b}{c}'?

开发者 https://www.devze.com 2023-02-16 03:28 出处:网络
I have an object that looks like var obj = { a: { a: { a: \'value\' } }, b: { a: { a: \'value2\' }, b: { a: \'value3\'

I have an object that looks like

var obj = {
   a: {
      a: {
         a: 'value'
      }
   },
   b: {
      a: {
         a: 'value2'
      },
      b: {
         a: 'value3'
      开发者_JAVA百科}
   }
}

I have a function which gets given a mask that looks like {b}{a}{a} what I want to do is get the value at obj.b.a.a how can I do this?


Slice off the first and last character, split by }{, and then recursively access the object with each element in turn (since foo.bar and foo['bar'] are equivalent).


This will work if your mask always has three properties. If not, you can write a function that does something similar:

var mask = "{a}{b}{c}";
var props = mask.replace(/{|}/g, "");

obj[props[0]][props[1]][props[2]];


obj.getMask = function(s) {
  var o=this, attrs=s.slice(1,s.length-1).split("\}\{");
  while (attrs.length > 0) {
    o = o[attrs.shift()];
    if (!o) return null;
  }
  return o;
};
obj.getMask("{a}{a}{a}"); // => "value"
obj.getMask("{b}{a}{a}"); // => "value1"
obj.getMask("{x}{y}{z}"); // => null

Of course, you can change the signature to pass in "obj" instead of using this if you don't want to muck up the object itself.


You can use reduce rather than use recursion. Here's a one-liner:

function index(obj, indexList) {
    return indexList.reduce(function(obj,x){return obj[x]}, obj);
}

function indexWithMask(mask) {
    return index(obj, mask.slice(1,-1).split('}{'));
}


Here is my code without using eval. Its easy to understand too.

function value(obj, props) {
  if (!props) return obj;
  var propsArr = props.split('.');
  var prop = propsArr.splice(0, 1);
  return value(obj[prop], propsArr.join('.'));
}

var obj = { a: { b: '1', c: '2', d:{a:{b:'blah'}}}};

console.log(value(obj, 'a.d.a.b')); //returns blah

If you are still using the mask part, you can modify a bit on the code.

function value(obj, props) {
    if (!props) return obj;
    var propsArr = props.match(/\{[a-zA-Z1-9]+\}/g);
    var prop = propsArr.splice(0, 1);
    return value(obj[prop[0].replace('{', '').replace('}', '')], propsArr.join(''));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号