使用Javascript检查JSON对象是否包含值
Use Javascript to check if JSON object contain value
我想检查JSON对象中的某个键是否包含某个值。假设我想要检查键"name"在任何对象中的值是否为"Blofeld"(为真)。我该怎么做呢?
[ {
"id" : 19,
"cost" : 400,
"name" : "Arkansas",
"height" : 198,
"weight" : 35
}, {
"id" : 21,
"cost" : 250,
"name" : "Blofeld",
"height" : 216,
"weight" : 54
}, {
"id" : 38,
"cost" : 450,
"name" : "Gollum",
"height" : 147,
"weight" : 22
} ]
您也可以使用Array.some()
函数:
const arr = [
{
id: 19,
cost: 400,
name: 'Arkansas',
height: 198,
weight: 35
},
{
id: 21,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
},
{
id: 38,
cost: 450,
name: 'Gollum',
height: 147,
weight: 22
}
];
console.log(arr.some(item => item.name === 'Blofeld'));
console.log(arr.some(item => item.name === 'Blofeld2'));
// search for object using lodash
const objToFind1 = {
id: 21,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
};
const objToFind2 = {
id: 211,
cost: 250,
name: 'Blofeld',
height: 216,
weight: 54
};
console.log(arr.some(item => _.isEqual(item, objToFind1)));
console.log(arr.some(item => _.isEqual(item, objToFind2)));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
这将给你一个数组,其中的元素与name === "Blofeld"匹配:
var data = [ {
"id" : 19,
"cost" : 400,
"name" : "Arkansas",
"height" : 198,
"weight" : 35
}, {
"id" : 21,
"cost" : 250,
"name" : "Blofeld",
"height" : 216,
"weight" : 54
}, {
"id" : 38,
"cost" : 450,
"name" : "Gollum",
"height" : 147,
"weight" : 22
} ];
var result = data.filter(x => x.name === "Blofeld");
console.log(result);
编写一个简单的函数来检查对象数组是否包含特定的值
var arr = [{
"name": "Blofeld",
"weight": 54
}, {
"name": "",
"weight": 22
}];
function contains(arr, key, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i][key] === val) return true;
}
return false;
}
console.log(contains(arr, "name", "Blofeld")); //true
console.log(contains(arr, "weight", 22)); //true
console.log(contains(arr, "weight", "22")); //false (or true if you change === to ==)
console.log(contains(arr, "name", "Me")); //false
使用hasOwnProperty()对数组中的所有对象进行简单的循环:
var json = [...];
var wantedKey = ''; // your key here
var wantedVal = ''; // your value here
for(var i = 0; i < json.length; i++){
if(json[i].hasOwnProperty(wantedKey) && json[i][wantedKey] === wantedVal) {
// it happened.
break;
}
}
相关文章:
- immutablejs:查找映射是否包含键值
- 谷歌脚本查看文本是否包含值
- 检查对象数组是否包含布尔值true/false
- 检查值是否包含字符串字符
- 根据对象中的值是否包含字符串来删除该值
- JavaScript 来检查 HTML 输入值是否包含字母和数字
- Javascript:如何检查数组是否包含某些值
- 测试数组是否包含八个 3 键值中的任何一个 - 井字游戏
- 如何检查javascript变量中的值是否包含数字
- 检查是否所有返回的数组都包含值 false
- 如何检查json对象是否包含值
- 检查变量是否包含数组的任何值
- 如何检查数组是否已设置并同时包含值
- JavaScript/jQuery检查数组是否包含所有特定值
- 检查对象是否包含带值的属性
- 使用Javascript检查JSON对象是否包含值
- 检查数组是否包含值?(我已经尝试了一些技巧,但我还是有点迷路了)
- 使用javascript检查URL是否包含值
- 如何检查iFrame中是否包含值
- Javascript检查数组是否包含值