[英]Get specific array value javascript
我不确定自己是否很傻,虽然我无法在任何地方找到它,但是我正在json_encode()
一些数据库输出并将其输出到页面,并使用$.parseJSON
读取,但是我想从数组中获取一个特定的值。 这是我要完成的示例。
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';
var json = $.parseJSON(j);
$(json).each(function(i, val) {
$.each(val, function(k, v) {
console.log(k['uid']) // <-- This is where I want to just output the UID from each array results
});
现在,我要完成的工作就是从此数组中提取UID(或name或profile_img,通常是一个值),以便稍后将这些值插入div中。
非常感谢您的帮助,谢谢!
.each
因为没有嵌套数组。 callback
第二个参数(为每个元素执行的函数)是当前循环中迭代的项,而不是第一个参数。 var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]'; var json = $.parseJSON(j); $(json).each(function(i, val) { console.log(val['uid']); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
我会避免使用jQuery
进行此操作。
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]'; var parsed = JSON.parse(j); var uids = parsed.map(function(item) { return item.uid; }); console.log(uids);
each
级别都不需要第二级。
尝试这个:
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]'; var json = $.parseJSON(j); $.each(json, function (i, obj) { console.log(obj.uid); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
尝试这个 :-
仅使用JS:
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';
j = JSON.parse(j);
j.map((value)=>{
console.log(value['uid'])
});
使用jQuery:-
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';
var json = $.parseJSON(j);
$(json).each(function(i, val) {
console.log(val['uid']);
});
将您的json对象解析为数组列表后,您可以使用如下所示的vanilla map函数
function stuff(item,index) {
//Here can do any manipulation with your object
return item.uid;
}
function myFunction() {
document.getElementById("myDiv").innerHTML = myArrayList.map(stuff);
}
这可能对您有帮助。
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';
var json = $.parseJSON(j);
var l=json.length;
var arr=[];
for(var i=0;i<l;i++){
arr.push(json[i]['uid']);
}
console.log(arr);//you can use this array for whatever purpose you intend to
不必使用Jquery!
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';
var parsedJson = JSON.parse(j);
var uidsArray = parsedJson.map( function(entry){
return entry.uid;
});
console.log(uidsArray); // output: [1,2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.