2014-09-30 54 views
0

我有这个阵列创造价值形式arryay Jquery?

var activeId = 1; 

var getAll = [{ 
    "id": "1", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}, { 
    "id": "2", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}] 

我需要的是与activeId = 1来获得唯一成员,并且不是创建新的变种,我可以提醒?

尝试过这样的事情,但我没有运气?

$.each(getAll, function(_, val) { 
    if (val.id == activeId) { 
     name = val.name; 
     position = val.position; 
     office = val.office; 
    } 
}); 

alert(position); 
+0

的警报没有显示。 – 2014-09-30 12:09:35

+0

它显示,但在所有名称,位置,办公室我得到了相同的结果? – Schneider 2014-09-30 12:11:12

回答

1

您可以使用​​功能。

var activeId = 1; 
 

 
var getAll = [{ 
 
    "id": "1", 
 
    "name": "John", 
 
    "position": "CEo", 
 
    "office": "NY", 
 
    "active": "Yes" 
 

 
}, { 
 
    "id": "2", 
 
    "name": "John", 
 
    "position": "CEowe", 
 
    "office": "NY", 
 
    "active": "Yes" 
 

 
}]; 
 

 
var filtered = jQuery.grep(getAll, function(n, i) { 
 
    return (n.id == activeId); 
 
}); 
 

 
for (var item in filtered) { 
 
    document.write("Id:" + filtered[item].id + " Name:" + filtered[item].name + " position:" + filtered[item].position); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

0

请更新您的阵列

VAR activeId = 1;

var getAll = [{ 
    "id": "1", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}, { 
    "id": "2", 
    "name": "Austin", 
    "position": "Manager", 
    "office": "US", 
    "active": "Yes" 

}] 
0

你应该声明变量循环:)外

http://jsfiddle.net/gwwtukha/3/

var name, position, office; 

$.each(getAll, function (_, val) { 
if (val.id == activeId) { 
    name = val.name; 
    position = val.position; 
    office = val.office; 
    //alert(position); 
} 
}); 
alert(position); 
+0

但是如何在主要作用域中声明该var? – Schneider 2014-09-30 12:15:12

+0

我已经做了修改,检查编辑的答案:) – 2014-09-30 12:15:31

0

试试这个:

var getAll = [{ 
    "id": "1", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 

}, { 
    "id": "2", 
    "name": "John", 
    "position": "CEo", 
    "office": "NY", 
    "active": "Yes" 
}]; 

getAll = $.map(getAll, function (item) { 
    return (item['active'] === 'Yes'? item : null); 
}); 

这会给你与两个对象的数组,你不能提醒这些用户,你必须使它们成为一种格式警报,可以处理如严格G:

getAll = JSON.stringify(getAll); 
alert(getAll); 

但你可以随时检查检查员工具的项目,如果您打印到控制台,像这样:

console.log(getAll);