javascript - 数组对象操作来创建新对象

标签 javascript

var actual = [
 {"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
 {"country":"AUSTRIA","month":"JAN","SR":"Brad    P","AC":"64","PR":"12","TR":1700},
 {"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},

 {"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
 {"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
 {"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},

 {"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
 {"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
 {"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
 ];

var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];

我有一组对象,需要为另一项工作 reshape 它们。需要一些操作来通过一个函数进行转换。我创建了 plunker https://jsbin.com/himawakaju/edit?html,js,console,output

主要因素是月份、国家/地区及其“AC”值。

最佳答案

循环,创建一个对象,然后循环创建数组

var actual = [
 {"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
 {"country":"AUSTRIA","month":"JAN","SR":"Brad    P","AC":"64","PR":"12","TR":1700},
 {"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},

 {"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
 {"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
 {"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},

 {"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
 {"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
 {"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
 ];

var outTemp = {};
actual.forEach(function(obj){ //loop through array
    //see if we saw the month already, if not create it
    if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
    outTemp[obj.month].val[obj.country] = obj.AC;  //add the country with value
});
var expected = [];  //convert the object to the array format that was expected
for (var p in outTemp) {
    expected.push(outTemp[p]);
}
console.log(expected);

关于javascript - 数组对象操作来创建新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31566899/

相关文章:

javascript - VueJS 从根 Vue 实例中的组件访问数据

javascript - 在 Angular 中,如何将服务注入(inject) Controller ?

javascript - 复制 URL 参数并粘贴到 HTML 上

javascript - 引用属性而不是 getter 和 setter

javascript - 下拉菜单(选择)——选择一个项目,并根据选择显示图片

javascript - 使用 JavaScript 获取不可见文本

javascript - 正则表达式不接受单个字符

javascript - 通过 chrome 扩展检查 cookie 是否存在

javascript - 将内容包裹在父元素中

javascript - 循环玩石头剪刀布游戏