JavaScript中的JSON组对象
假设我们有一个像这样的对象数组-
const arr = [
{ 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
{ 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
{ 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
{ 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
];我们需要编写一个JavaScript函数,该函数接受一个这样的对象数组。该函数应映射从对象中删除“值”和“类型”键,并将它们的值作为键值对添加到相应的对象。
因此,上述输入的输出应如下所示:
const output = [
{ 'name': 'JON', 'flight':100, 'uns': 12, 'sch': 35 },
{ 'name': 'BILL', 'flight':200, 'uns': 33, 'sch': 45}
];输出结果
为此的代码将是-
const arr = [
{ 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' },
{ 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' },
{ 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' },
{ 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' }
];
const groupArray = (arr = []) => {
const res = arr.reduce(function (hash) {
return function (r, o) {
if (!hash[o.name]) {
hash[o.name] = { name: o.name, flight: o.flight };
r.push(hash[o.name]);
}
hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value;
return r;
}
}(Object.create(null)), []);
return res;
};
console.log(groupArray(arr));输出结果
控制台中的输出将是-
[
{ name: 'JON', flight: 100, uns: 12, sch: 35 },
{ name: 'BILL', flight: 200, uns: 33, sch: 45 }
]