我有一个关于javascript中的for循环或使用 Angular 方式输出结果对象列表的问题。
我有一个对象列表如下
var alist = [];
alist = [
{ 'code': 1000, 'type': 'C', 'a': 4, 'b': null, 'c': null },
{ 'code': 1000, 'type': 'C', 'a': null, 'b': null, 'c': 6 },
{ 'code': 1500, 'type': 'O', 'a': null, 'b': null, 'c': 8 },
{ 'code': 1500, 'type': 'O', 'a': null, 'b': 8, 'c': null },
{ 'code': 1000, 'type': 'O', 'a': 7, 'b': null, 'c': null },
{ 'code': 1000, 'type': 'C', 'a': null, 'b': 7, 'c': null },
{ 'code': 2000, 'type': 'C', 'a': 4, 'b': null, 'c': null },
{ 'code': 2000, 'type': 'C', 'a': null, 'b': 6, 'c': 12 },
{ 'code': 3000, 'type': 'C', 'a': 1, 'b': null, 'c': 12 },
{ 'code': 3000, 'type': 'C', 'a': null, 'b': 6, 'c': null }
];
我想要的结果是组合相同的代码+相同的类型并组合a、b、c值。 这是我想要的结果。
var resultList = [];
resultList = [
{ 'code': 1000, 'type': 'C', 'a': 4, 'b': 7, 'c': 6 },
{ 'code': 1500, 'type': 'O', 'a': null, 'b': 8, 'c': 8 },
{ 'code': 1000, 'type': 'O', 'a': 7, 'b': null, 'c': null },
{ 'code': 2000, 'type': 'C', 'a': 4, 'b': 6, 'c': 12 },
{ 'code': 3000, 'type': 'C', 'a': 1, 'b': 6, 'c': 12 },
];
要点:
- 代码是动态的,而不是 1000、1500、2000 的硬编码。
- 一个代码仅绑定(bind)一种类型,因此如果 1000 个代码仅包含一种类型 C。
可以输出这个结果吗?
我尝试过jsfiddle ,但我仍然没有输出结果列表。
最佳答案
您可以使用一些辅助数组作为要收集的键和参数以及要分组的对象。
var data = [{ code: 1000, type: 'C', a: 4, b: null, c: null }, { code: 1000, type: 'C', a: null, b: null, c: 6 }, { code: 1500, 'type': 'O', a: null, b: null, c: 8 }, { code: 1500, type: 'O', a: null, b: 8, c: null }, { code: 1000, type: 'O', a: 7, b: null, c: null }, { code: 1000, type: 'C', a: null, b: 7, c: null }, { code: 2000, 'type': 'C', a: 4, b: null, c: null }, { code: 2000, type: 'C', a: null, b: 6, c: 12 }, { code: 3000, type: 'C', a: 1, b: null, c: 12 }, { 'code': 3000, type: 'C', a: null, b: 6, c: null }],
keys = ['code', 'type'],
values = ['a', 'b', 'c'],
grouped = [];
data.forEach(function (a) {
var key = keys.map(function (k) { return a[k]; }).join('|');
if (!this[key]) {
this[key] = {};
keys.forEach(function (k) { this[k] = a[k]; }, this[key]);
values.forEach(function (k) { this[k] = null; }, this[key]);
grouped.push(this[key]);
}
values.forEach(function (k) {
if (a[k] !== null) {
this[k] = (this[k] || 0) + a[k];
}
}, this[key]);
}, Object.create(null));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何以 JavaScript 或 Angular 方式返回此结果对象格式列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39858875/