Reputation: 3915
I have a large object:
var json = {
"userRole": "Admin",
"assetDtlsList": [{
"machineId": "1A",
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
},{
"machineId": "2A",
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
},{
"machineId": "3A",
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
}],
"count": 0
}
Now i want to get all the "machineId" in a array
I tried :
$.each(json, function (key, data) {
console.log(key)
$.each(data, function (index, data) {
console.log(data.machineId)
// push data to array
})
})
but not working?
please help!
Upvotes: 0
Views: 48
Reputation: 3148
Your JSON is invalid. the valid json is:
{
"userRole": "Admin",
"assetDtlsList": [ //Missing bracket
{
"machineId": "1A", // Missing quotes
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
},
{
"machineId": "2A", // Missing quotes
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
},
{
"machineId": "3A", // Missing quotes
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
}
],
"count": 0
}
Now use this code to get machine id:
$.each(abc.assetDtlsList, function (key, data) {
console.log(data.machineId);
});
Edit: To push the properties to array, Use this code:
var mIDs = [];
$.each(abc.assetDtlsList, function (key, data) {
mIDs.push(data.machineId);
});
Upvotes: 3
Reputation: 63524
Use map
:
var machineIds = json.assetDtlsList.map(function (el) {
return el.machineId;
});
Upvotes: 0
Reputation: 337560
Once you correct your object's syntax:
var json = {
"userRole": "Admin",
"assetDtlsList": [{
"machineId": "1A",
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
},{
"machineId": "2A",
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
},{
"machineId": "3A",
"serialNo": "123",
"lon": "-78.80472",
"totalFuel": "685.3"
}],
"count": 0
}
You can create an array of the machineId
properties with a simple loop:
var machineIds = [];
$.each(json.assetDtlsList, function(i, obj) {
machineIds.push(obj.machineId);
});
console.log(machineIds); // = [ "1A", "2A", "3A" ]
Upvotes: 3
Reputation: 130
Try this,
var temp = [];
$.each(json,function(row,val){
if(typeof val == "object"){
$.each(val,function(r,v){
if(v.machineId)
temp.push(v.machineId);
});
}
})
Upvotes: -1