我正在尝试从我的对象中的某个属性中删除时间。实际上我检查: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")
}
}
})
原始数组应保持不变,结果应在单独的数组中捕获。
这是小提琴的链接。
答案 0 :(得分:3)
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)
<强> OUTPUTS 强>
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)
答案 1 :(得分:1)
您可以将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(' ');
};
答案 2 :(得分:1)
最好的办法是将日期解析为Date对象,然后重新格式化。您可以根据自己的喜好对其进行格式化,无论是否有时间。有许多库可用于格式化日期。你声明你使用的是jQuery,有一个日期格式的插件。
我不建议您尝试将字符串分解为片段。有许多日期格式(您不必指定此日期的来源),您的解决方案将来很容易停止工作。
答案 3 :(得分:0)
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*GMT\s*/g, '');
}
console.info(ary);