반응형
Javascript를 사용하여 JSON 개체에 값이 포함되어 있는지 확인합니다.
아래와 같은 JSON 오브젝트의 특정 키에 특정 값이 포함되어 있는지 확인하고 싶습니다.오브젝트 중 하나에서 키 "name"이 값 "Blefeld"(참)를 가지고 있는지 여부를 확인한다고 가정합니다.내가 어떻게 그럴 수 있을까?
[ {
"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>
그러면 이름이 === "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;
}
}
언급URL : https://stackoverflow.com/questions/40438851/use-javascript-to-check-if-json-object-contain-value
반응형
'programing' 카테고리의 다른 글
Symfony2, 액션이 Ajax에서 호출되는지 확인합니다. (0) | 2023.03.26 |
---|---|
Twig+ Wordpress - 어레이 인수를 기능에 전달하는 방법 (0) | 2023.03.26 |
servlets 3.0 API에서의 비동기 지원을 이해할 수 없습니다. (0) | 2023.03.26 |
angularjs 약속을 돌려주기 전에 해결할 수 있나요? (0) | 2023.03.26 |
wordpress 배열에 wp_param을 추가하는 방법 (0) | 2023.03.26 |