在AngularJS / Javascript中我有一个对象数组,这些对象包含一个日期。我想按日期订购这些对象,并将属性添加到具有特定日期时间的最后一个对象。因此,如果2个对象具有相同的日期,我想将属性添加到具有最新时间的属性。如果只有一个对象有一个日期,我想将属性添加到该对象。
一个例子:
input: var arr = [
{A: {"Date": "2017-08-14T15:15:00"} B:{}}
{A: {"Date": "2017-08-14T16:15:00"} B:{}} //<--- Add attribute to this object
]
output: var arr = [
{A: {"Date": "2017-08-14T15:15:00"} B:{}}
{A: {"Date": "2017-08-14T16:15:00"} B:{} C:{"NewAttribute": "true"}}
]
我如何编程呢?最初我在考虑使用for循环来比较所有对象,但我不知道如何实现它。
答案 0 :(得分:1)
我希望我理解你想要的东西:
var arr = [
{A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // won't get the new property
{A: {"Date": "2017-08-14T16:12:00"}, B:{}}, // will get the new property
{A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // will get the new property
{A: {"Date": "2017-08-14T16:14:00"}, B:{}}, // won't get the new property
{A: {"Date": "2017-08-14T16:14:00"}, B:{}} // will get the new property
];
// sort the array by date in descending order
var sorted = arr.sort(({A: { Date: d1 }}, {A: { Date: d2 }}) => new Date(d2).getTime() - new Date(d1).getTime());
// eventually add the new property
sorted.reduce((acc, o) => {
var date = o.A.Date;
if (acc !== date) {
// the date isn't equal to the date of the last item, so it's
// either the only item with that date
// or the first (in reversed order) item with that date
o.C = {"NewAttribute": "true"};
}
return date;
}, '');
// reverse the array
var result = sorted.slice().reverse();
console.log(result);
&#13;
答案 1 :(得分:0)
您可以先使用Array.prototype.sort()按日期对数组进行排序,然后将新属性添加到最后一个元素:
var arr = [
{A: {"Date": "2017-08-14T15:15:00"},B: {}},
{A: {"Date": "2017-08-16T16:15:00"},B: {}},
{A: {"Date": "2017-08-24T16:15:00"},B: {}},
{A: {"Date": "2017-08-24T16:15:00"},B: {}, C: {}}
],
alphabetArr = 'abcdefghijklmnopqrstuvwxyz'
.toLocaleUpperCase()
.split(''),
lastElementLength = 0;
// Sort the array
arr.sort(function (a, b) {
return new Date(b.A.date) - new Date(a.A.date);
});
// Get last element properties length
lastElementLength = Object.keys(arr[arr.length - 1]).length;
// Adds new attribute to last element with the proper name..
arr[arr.length - 1][alphabetArr[lastElementLength]] = {
"NewAttribute": "true"
};
console.log(arr);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;