Javascript 在 JSON 对象数组中找到一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29936971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
find a value inside array of JSON object
提问by ScrapCode
I get below Array of JSON objects from JSP
我从 JSP 得到以下 JSON 对象数组
"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.
在 JS 方面,它被解析,我看到一个包含 3 个对象的数组。现在,我想在传递 String 键时查找/识别一个值。
For e.g. when I pass "Book2" I should get value "BULLETIN 2". Can someone help me identify the approach?
例如,当我通过“Book2”时,我应该得到值“BULLETIN 2”。有人可以帮我确定方法吗?
采纳答案by Alexander T.
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));
回答by rubikonx9
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 grepinstead of filter:
此外,如果您使用的是jQuery,则可以使用grep代替filter:
jQuery.grep(x, function(value) {
return value.hasOwnProperty(key);
}) /* and so on */;
回答by cн?dk
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.
我们使用element[key]whereelement is array[el]来获取给定 的值key。
回答by kasimoglou
For such array/collection manipulation in Javascript I would suggest you to use underscorejslibrary. It provides functions that, to me, make everything much more simple. In your case:
对于 Javascript 中的此类数组/集合操作,我建议您使用underscorejs库。它提供的功能对我来说使一切变得更加简单。在你的情况下:
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;
}
}
Hereis a working fiddle of what I am suggesting.
这是我建议的工作小提琴。
回答by Stefan Wittwer
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".
解决方案:现在你可以做类似的事情getObjectInArray(titlesJSONArray, "Book2"),它应该返回“BULLETIN 2”。
var titlesJSONArray = [ { "Book3": "BULLETIN 3" }, ... ]; // and so on
var book2 = getObjectInArray(titlesJSONArray, "Book2"); // => "BULLETIN 2"

