我试图从我的对象属性之一删除时间。实际上,我用:index检查时间戳是否存在于属性值中。实际上我有这个
输入[
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:38:05 GMT 2015"
},
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:35:05 GMT 2015"
}
]
输出[
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 2015"
},
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 2015"
}
]
Javascript var object = ary.map(function(o){
var result={}
// console.log(o)
for(i in o){
console.log(i+":"+o[i]) ;
if(o[i].indexOf(":")!=-1){
console.log("timestam present")
}
}
})
原始数组应保持不变,结果应在单独的数组中捕获。
var ary=[
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:38:05 GMT 2015"
},
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:35:05 GMT 2015"
}]
ary.map(function(o){
var d = new Date(o.C);
o.C = d.toDateString();
})
console.dir(ary)
C: "Mon Apr 13 2015"
S: "Charge Interest Against Past Due Account"
C: "Mon Apr 13 2015"
S: "Charge Interest Against Past Due Account"
保留原始对象,并在其他对象中获取结果,使用以下代码:
var ary=[
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:38:05 GMT 2015"
},
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:35:05 GMT 2015"
}]
var a = ary.map(function(o){
var result = {};
var d = new Date(o.C);
result.S = o.S;
result.C = d.toDateString();
return result;
})
console.dir(a)
最好的方法是将日期解析为date对象,然后重新格式化。您可以按照自己的喜好设置格式,有或没有时间。有许多库可用于格式化日期。你说你使用的是jQuery,有一个日期格式的插件。
我不建议您尝试将字符串分成片段。有许多日期格式(您不指定该日期来自何处),并且您的解决方案可以很容易地在将来停止工作。
您可以用空格分隔C
属性,然后重新连接您想要保留的部分。试试这个:
for (var i = 0; i < ary.length; i++) {
var dateValues = ary[i].C.split(' ');
ary[i].C = dateValues[0] + ' ' + dateValues[1] + ' ' + dateValues[2] + ' ' + dateValues[5]
};
更新小提琴
没有丑陋的字符串连接的替代方案:
for (var i = 0; i < ary.length; i++) {
var dateValues = ary[i].C.split(' ')
dateValues.splice(3, 2);
ary[i].C = dateValues.join(' ');
};
var ary = [
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:38:05 GMT 2015"
},
{
"S": "Charge Interest Against Past Due Account",
"C": "Mon Apr 13 10:35:05 GMT 2015"
}];
for (var i = 0; i < ary.length; i++) {
ary[i].C = ary[i].C.replace(/d+:d+:d+s*GMTs*/g, '');
}
console.info(ary);