循环以基于键获取对象的值

时间:2015-07-01 10:10:00

标签: javascript jquery arrays json

我有一个大对象:

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
}

现在我想得到所有" machineId"在数组中

我试过了:

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log(data.machineId)
        // push data to array
    })
})

但没有工作?

请帮忙!

4 个答案:

答案 0 :(得分:3)

您的JSON无效。有效的json是:

{
    "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
}

现在使用此代码获取计算机ID:

$.each(abc.assetDtlsList, function (key, data) {
    console.log(data.machineId);
});

编辑:要将属性推送到数组,请使用以下代码:

var mIDs = []; 
$.each(abc.assetDtlsList, function (key, data) {
      mIDs.push(data.machineId);
});

答案 1 :(得分:3)

一旦你纠正了对象的语法:

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
}

您可以使用简单的循环创建machineId属性的数组:

var machineIds = [];
$.each(json.assetDtlsList, function(i, obj) {
    machineIds.push(obj.machineId);
});

console.log(machineIds); // = [ "1A", "2A", "3A" ]

Example fiddle

答案 2 :(得分:0)

使用map

var machineIds = json.assetDtlsList.map(function (el) {
  return el.machineId;
});

DEMO

答案 3 :(得分:-1)

试试这个,

var temp = [];
$.each(json,function(row,val){
	if(typeof val ==  "object"){
		$.each(val,function(r,v){
			if(v.machineId)
				temp.push(v.machineId);
		});
	}
})