Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find a value inside array of JSON object [closed]

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?

like image 436
ScrapCode Avatar asked Apr 29 '15 07:04

ScrapCode


3 Answers

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));
like image 96
Oleksandr T. Avatar answered Oct 14 '22 13:10

Oleksandr T.


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 */;
like image 5
rubikonx9 Avatar answered Oct 14 '22 11:10

rubikonx9


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.

like image 4
cнŝdk Avatar answered Oct 14 '22 12:10

cнŝdk