9
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.

2
  • 1
    Take a look to this: goessner.net/articles/JsonPath Commented Jun 3, 2016 at 9:58
  • @ADreNaLiNe-DJ Very interesting! Commented Jun 3, 2016 at 10:00

5 Answers 5

32

Use Array#reduce() method

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);

Sign up to request clarification or add additional context in comments.

3 Comments

How we can do it in somw string like `’i.want.it bro’ I mean it contains another texts but we only use . part of it do you know how to do it
How would you do it if the object contains arrays?
@Dolan data.0.prop
2

This will work :

var give = 'i.want.it';

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

console.log( eval("obj."+give));

Live DEMO JSFiddle

This is a really easy way to do it, but not safe, i don't advise you to use it for professional use. Use previous answer they looks good.

1 Comment

This solution works with complicated JSON objects too which contains arrays. Upvoted.
2

make it

var obj = {
    i: {
        want: {
            it: 'Oh I know you do...'
        }
    }
};
//var result = JSON.parse(JSON.stringify(obj)); //cloning the existing obj
var result = obj; //cloning the existing obj
var give = 'i.want.it';

//now split the give and iterate through keys
give.split(".").forEach(function(key){
  result = result[key];
});
console.log(result);

2 Comments

Hmm pretty nifty! I'll try it out and get back.
Cloning the object is not necessary. It would be enough to assign obj to another reference (var result = obj;).
1

You can use eval()

var obj = {"a": { "b": { "c": 3}}}; writeln(eval('obj.a.b.c') + 2);

This will output 5.

JavaScript is weakly typed and thus it's evaluation function executes a statement as well as evaluating an expression.

Comments

0

@nina-scholz posted this here in 2016, and then deleted it. But TBH, I think it was the best answer ? ES6.

var give = 'i.want.it';

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

console.log(give.split('.').reduce((r, a) => r && r[a], obj));

// 'Oh I know you do...'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.