2015-07-21 55 views
0

我有一个字段返回JSON格式的结果。迭代数组以获取值。

$('#selectCategory').on('change', function() { 
    var optionSelect = $(this).val(); 
    console.log('The option selected is: ' + optionSelect); 
    $.post("{{path('playlist_category') }}", {category: optionSelect}, 
     function (filterContent) { 
      console.log(filterContent); 
     }, 'json'); 
}); 

的filterContent函数返回一个类似的结果:

console result

但我只想留在有关资料元素的“身份证”。

如果我这样做,控制台返回是这样的:

function (filterContent) { 
    for (var content in filterContent.category_result) { 
     for (var data in filterContent.category_result[content]) { 
      var result = filterContent.category_result[content][data]; 
       console.log(result); 
     } 
    } 
}, 'json'); 

Console result 2

怎么可能只获得数据的 '身份证'?

谢谢!

回答

1

无需内部for-in循环使用这样

function (filterContent) { 
    for (var content in filterContent.category_result) { 
     console.log(filterContent.category_result[content].id) 

    } 
}, 'json'); 
1

使用此代码来代替:

$.post("{{path('playlist_category') }}", {category: optionSelect}, 
    function (filterContent) { 
     for(var i = 0; i < filterContent.category_result.length; i++) { 
     console.log('id', filterContent.category_result[i]['id']); 
     } 
    } 
}, 'json'); 
0

尽量使结果作为JSON的。我试图调整你的函数(filterContent)

function (filterContent) { 
var result={}; 
    for (var content in filterContent.category_result) { 
     for (var data in filterContent.category_result[content]) { 
      result.id = filterContent.category_result[content][id]; 
      result.data= filterContent.category_result[content][data]; 
       console.log(result); 
     } 
    } 
}, 'json'); 
0

你可以试试这个获得一组ID:

function (filterContent) { 
    var ids = $(filterContent.category_result).map(function() { return this.id }); 
} 
+0

这个答案是不完整的,语法错了,你也不需要使用jQuery来执行一个映射。 –

+0

@Mike C浏览器兼容性IE9 +不使用jQuery的地图。你为什么认为它在语法上是错误的?不完整?你认为这个人会做什么?他会在控制台上打印输出,或者他想收集ID?我敢打赌,他的想法是在控制台中收集ID而不是打印。 – Reflective

+0

该函数缺少名称,也不是另一个对象中的属性。你收集身份证然后不做任何事。 –