发现如果一个JSON值中包含某些文字
问题描述:
我不知道这是可能的,因为我还没有发现这样的东西.. 我通过一个JSON对象去..发现如果一个JSON值中包含某些文字
{"name": "zack",
"message": "hello",
"time": "US 15:00:00"},
{"name": "zack",
"message": "hello",
"time": "US 00:00:00"}
有我可以选择只包含“15:00:00”部分的时间属性的方式?
感谢您的帮助
答
按我的理解,如果你分析你的JSON你有对象的数组。所以,你可以利用filter功能和过滤掉不符合您在过滤功能通过标准的那些要素:
var parsedJson = [{"name": "zack",
"message": "hello",
"time": "US 15:00:00"},{"name": "zack",
"message": "hello",
"time": "US 00:00:00"}];
var result = parsedJson.filter(item=>item.time === "US 15:00:00");
console.log(result);
答
您可以使用阵列#过滤功能。它将返回一个带有匹配元素的新数组。如果新的数组的长度是0,那么没有找到匹配
var myJson = [{
"name": "zack",
"message": "hello",
"time": "US 15:00:00"
},
{
"name": "zack",
"message": "hello",
"time": "US 00:00:00"
}
]
var m = myJson.filter(function(item) {
return item.time === "US 15:00:00"
})
console.log(m)
findIndex还可以用于找到如果它包含的值。如果该值是-1意思JSON数组中不包含与条件匹配的任何对象
var myJson = [{
"name": "zack",
"message": "hello",
"time": "US 15:00:00"
},
{
"name": "zack",
"message": "hello",
"time": "US 00:00:00"
}
]
var m = myJson.findIndex(function(item) {
return item.time === "US 15:00:00"
});
console.log(m)
答
var arr = [{
"name": "zack",
"message": "hello",
"time": "US 15:00:00"
}, {
"name": "zack",
"message": "hello",
"time": "US 00:00:00"
}]
for (var i = 0; i < arr.length; i++) {
var time = (arr[i].time.split('US '))[1];
console.log(time);
}
如果发现的有用标记它作为有帮助的。
答
您可以使用filter
函数来过滤数组,并可以使用indexOf
来检查time
字段是否包含15:00:00
。
E.g:
var json = [{
"name": "zack",
"message": "hello",
"time": "US 15:00:00"
},
{
"name": "zack",
"message": "hello",
"time": "US 00:00:00"
}
];
var resultObj = json.filter(item=>item.time.indexOf("15:00:00") !== -1);
console.log(resultObj);
你能不能约你的意思有点更清晰?你选择什么意思? –