I Have following JSON data, I need to iterate this data based on Keytype in JAVASCRIPT. It should return record from only the passed key code. Say i need record from 438 means it should give me only following data. (ex:"K": "43800001", "D": "Data1")
{
"GroupCode": {
"PickType": [
{
"@KeyType": "438",
"R": [
{
"K": "43800001",
"D": "Data1"
}
]
},
{
"@KeyType": "439",
"R": [
{
"K": "43900001",
"D": "Data2"
}
]
},
{
"@KeyType": "440",
"R": [
{
"K": "44000001",
"D": "Data3"
}
]
},
{
"@KeyType": "441",
"R": [
{
"K": "44100001",
"D": "Data4"
}
]
}
]
}
}
as I'm not good in java script and new to it, i haven't tried coding for this. Please help me in getting the data.
-
JSON.parse parses JSONJaromanda X– Jaromanda X2016年02月04日 11:35:50 +00:00Commented Feb 4, 2016 at 11:35
-
you should try, not put it directlyParth Trivedi– Parth Trivedi2016年02月04日 11:36:01 +00:00Commented Feb 4, 2016 at 11:36
-
@JaromandaX Why would he needs to parse it? It is already js object in valid JSON formatA. Wolff– A. Wolff2016年02月04日 11:37:08 +00:00Commented Feb 4, 2016 at 11:37
-
I assumed from the question TITLE - my badJaromanda X– Jaromanda X2016年02月04日 11:37:49 +00:00Commented Feb 4, 2016 at 11:37
-
@JaromandaX Oh ya, then it would be the answer ;)A. Wolff– A. Wolff2016年02月04日 11:38:13 +00:00Commented Feb 4, 2016 at 11:38
4 Answers 4
Let us say the above is stored in a variable obj. You can get the result via following
var result = obj.GroupCode.PickType.filter(function(item){
return item["@KeyType"] === "438"
}).map(function(item){
return item.R[0];
});
Please note, result is an array. If you have unique object against the condition then for that you will have to check the length of array and then extract the object i.e. result[0] or result.shift()
8 Comments
.map(...)[0]obj.GroupCode.PickType.filter(function(item){ return item["@KeyType"] === "438" })[0].R[0]; But somehow, your code is more readablefunction getByKeyType(keytype) {
for(i in f.GroupCode.PickType) {
if(f.GroupCode.PickType[i].KeyType == keytype) {
return f.GroupCode.PickType[i].R[0];
}
}
return null;
}
alert(getByKeyType(438).K)
alert(getByKeyType(438).D)
Comments
Try this
function getByKeyType(keytype) {
for(i in f.GroupCode.PickType) {
if(f.GroupCode.PickType[i].KeyType == keytype) {
return f.GroupCode.PickType[i].R[0];
}
}
return null;
}
1 Comment
var result = JSON.parse(obj); I think obj in OP's code is already an objectTry a simple jquery each loop and a if:
jquery:
$.each(obj.GroupCode.PickType,function(i,v){
if (v["@KeyType"] == 438) {
console.log(v.R)//v.R[0];
}
});
javascript:
for(v in obj.GroupCode.PickType) {
if (v["@KeyType"] == 438) {
console.log(v.R)//v.R[0];
}
}
2 Comments
$.each is not a vanilla javascript , it comes with jQuery: a js lib. do not take it for granted knowledge. also op said he's new in javascript so maybe he'll get an error while testing your code and wondering "..why?", add some additional info