-1

I am have JSON object that looks like this,

Object {doors: Array[3], baseboards: Array[6], casings: Array[3], crown_mouldings: Array[1], panel_mouldings: Array[1]…}
    architraves: Array[1]
    baseboards: Array[6]
    casings: Array[3]
    chair_rails: Array[1]
    crown_mouldings: Array[1]
    doors: Array[3]
    panel_mouldings: Array[1]
    roofs: Array[8]

What I am wanting to know is I how can just get a certain section of the JSON object. Know obvioulsy I could do something like,

console.log(JSON.roofs) to return the roofs data. My query comes from not knowing what exactly the user will be requesting at anyone time, all I get back from the system is a string of tex, that could be any one of the keys.

Is there a way to search for a key in a JSON object and return that specific data if found?

I have tried this....

getData: function(obj, product) {
        console.log(obj);
        var a = obj;
        var index = 0;
        var found;
        var entry;
        for(index = 0; index < Object.keys(a).length; ++index) {
            console.log(index);
            console.log(a[1]);
            entry = a[index];
            console.log(entry);
        }
    },

The parameters of the above function obj = the json, product equals the string name of the key I am looking for. I get nothing returned. What is the best way to go about this?

Thanks!

Udders
  • 6,914
  • 24
  • 102
  • 194

2 Answers2

0

Use square bracket notation.

var userEnteredKey = "crown_mouldings";
var data = obj[userEnteredKey];
// Array[1]
Code Whisperer
  • 22,959
  • 20
  • 67
  • 85
0

Use the in operator to determine if the object has that key.

var key = 'doors';

if( key in obj )
{
    console.log( "The value assigned to the key '" + key + "' is:");
    console.log( obj[key] );
}
else
{
    console.log( "The key '" + key + "' is not in obj." );
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

iambriansreed
  • 21,935
  • 6
  • 63
  • 79