[英]Loop through multiple items in json and assign variable
I'm trying to loop through some json. 我正在尝试遍历一些json。 The json result looks like this:
json结果如下所示:
{
"items": [{
"metafield1": "May 22 2019"
}, {
"metafield1": null
}, {
"metafield1": null
}, {
"metafield1": "May 20 2019"
}]
}
I'm getting this in an ajax call that then assigns a variable and then checks if the variable exists. 我在ajax调用中得到了这个信息,然后分配了一个变量,然后检查该变量是否存在。
$.ajax({
type: 'GET',
url: '/cart?view=alternate.json',
success: function(result) {
var obj = JSON.parse(result);
var del_date = obj.metafield1;
if (del_date !== null) {
// do something
}
}
})
At first I only had one item in the json so this worked fine, but now as you can see I've got multiple so I need to loop through them and eventually compare them so basically I need to store each one of them as a variable. 最初,我在json中只有一个项目,因此效果很好,但是现在您可以看到我有多个项目,因此我需要遍历它们并最终进行比较,因此基本上我需要将每个项目都存储为一个变量。 Any ideas how to do this?
任何想法如何做到这一点?
You can handle your string like this use map function with [] operator 您可以使用[]运算符像这样使用map函数来处理您的字符串
var string = '[{ "metafield1": "May 22 2019" } , { "metafield1": null } ,
{ "metafield1": null } , { "metafield1": "May 20 2019" } ]';
var metafields = JSON.parse(string).map(function(v){ return v['metafield1']; });
console.log(metafields);
Updated with new object 更新了新对象
let result = {
"items": [{
"metafield1": "May 22 2019"
}, {
"metafield1": null
}, {
"metafield1": null
}, {
"metafield1": "May 20 2019"
}]
};
string = JSON.stringify(result.items);
var metafields = JSON.parse(string).map(function(v){ return v['metafield1']; });
console.log(metafields);
let result = { "items": [{ "metafield1": "May 22 2019" }, { "metafield1": null }, { "metafield1": null }, { "metafield1": "May 20 2019" }] }; //console.log(JSON.stringify(result.items)); //var string = '[{ "metafield1": "May 22 2019" } , { "metafield1": null } , { "metafield1": null } , { "metafield1": "May 20 2019" } ]'; string = JSON.stringify(result.items); var metafields = JSON.parse(string).map(function(v){ return v['metafield1']; }); console.log(metafields);
This should be working : 这应该工作:
// we set a variable x = to your JSON variable var x = { "items": [{ "metafield1": "May 22 2019" }, { "metafield1": null }, { "metafield1": null }, { "metafield1": "May 20 2019" }] }; // we update x to be equal to your item field from the object, x is now an array instead of an object x = x["items"]; for (var i of x) { if (i.metafield1 !== null) { console.log(i.metafield1); // your code here } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.