15

I get below Array of JSON objects from JSP

"Titles":[                          
    {
    "Book3" : "BULLETIN 3"
    }   
    ,
    {
    "Book1" : "BULLETIN 1"
    }
    ,
    {
    "Book2" : "BULLETIN 2"
    }    
]

On JS side, it is parsed and I see an array with 3 objects. Now, I want to find/identify a value when I pass String key.

For e.g. when I pass "Book2" I should get value "BULLETIN 2". Can someone help me identify the approach?

0

5 Answers 5

10

Try this

var data = {
    "Titles": [{
        "Book3": "BULLETIN 3"
    }, {
        "Book1": "BULLETIN 1"
    }, {
        "Book2": "BULLETIN 2"
    }]
};

function getValueByKey(key, data) {
    var i, len = data.length;
    
    for (i = 0; i < len; i++) {
        if (data[i] && data[i].hasOwnProperty(key)) {
            return data[i][key];
        }
    }
    
    return -1;
}

console.log(getValueByKey('Book2', data.Titles));

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

Comments

5

Having:

var x = [{
    "Book3" : "BULLETIN 3"
}, {
    "Book1" : "BULLETIN 1"
}, {
    "Book2" : "BULLETIN 2"
}];

and

var key = "Book1";

You can get the value using:

x.filter(function(value) {
    return value.hasOwnProperty(key); // Get only elements, which have such a key
}).shift()[key]; // Get actual value of first element with such a key

Notice that it'll throw an exception, if object doesn't have such a key defined.

Also, if there are more objects with such key, this returns the first one only. If you need to get all values from objects with such key, you can do:

x.filter(function(value) {
    return value.hasOwnProperty(key); // Get only elements, which have such a key
}).map(function(value) {
    return value[key]; // Extract the values only
});

This will give you an array containing the appropriate values only.

Additionally, if you're using jQuery, you can use grep instead of filter:

jQuery.grep(x, function(value) {
    return value.hasOwnProperty(key);
}) /* and so on */;

Comments

4

To achieve this, you have to loop through the array elements's keys and test if the given key exists in the array, if so get its value:

var jsonTitles = [                          
   { "Book3" : "BULLETIN 3" },
   { "Book1" : "BULLETIN 1" },
   { "Book2" : "BULLETIN 2" }    
]

function getValue(key, array) {
  for (var el in array) {
    if (array[el].hasOwnProperty(key)) {
      return array[el][key];
    }
  }
}

alert(getValue("Book1", jsonTitles));

We use element[key] where element is array[el] to get the value of the given key.

Comments

1

Let's create a function to get an object in an array for that, that takes two arguments: the array and the key of the property you want to get:

function getObjectInArray(arr, key) {    
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].hasOwnProperty(key)) return arr[i][key];
    }
}

This loops through each object looking for that specific key.


Solution: Now you could do something like getObjectInArray(titlesJSONArray, "Book2") and it should return "BULLETIN 2".

var titlesJSONArray = [ { "Book3": "BULLETIN 3" }, ... ]; // and so on
var book2 = getObjectInArray(titlesJSONArray, "Book2"); // => "BULLETIN 2"

Comments

1

For such array/collection manipulation in Javascript I would suggest you to use underscorejs library. It provides functions that, to me, make everything much more simple. In your case:

function find_value(array, key) {
    // find will run the provided function for every object in array
    var obj_found = _.find(array, function(obj) {
        // keys returns the keys inside an object
        // so if the key of currently examined object 
        // is what we are looking for, return the obj
        if (_.keys(obj)[0] === key) {
            return obj;
        }
   });
   // if an object with such key was found return its value
   if (obj_found) {
      return obj_found[key];
   } else {
      return null;
   }
}

Here is a working fiddle of what I am suggesting.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.