对象变换数组

时间:2016-03-08 11:44:58

标签: javascript

我有一系列像这样的对象:

[
  { week: 1, day: 1, todo: "eq1" },
  { week: 1, day: 3, todo: "eq2" },
  { week: 4, day: 6, todo: "eq3" },
  { week: 4, day: 7, todo: "eq4" },
]

我想转变成这样:

[ 
   1: {
       1: { todo: "eq1" },
       3: { todo: "eq2" }
   },
   4: {
       6: { todo: "eq3" },
       7: { todo: "eq4" }
   }
]

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我建议在待办事项列表中使用数组,因为列表中可能有多个项目要做。



var data = [{ week: 1, day: 1, todo: "eq1" }, { week: 1, day: 3, todo: "eq2" }, { week: 4, day: 6, todo: "eq3" }, { week: 4, day: 7, todo: "eq4" }],
    object = function (data) {
        var r = {};
        data.forEach(function (a) {
            r[a.week] = r[a.week] || {};
            r[a.week][a.day] = r[a.week][a.day] || [];
            r[a.week][a.day].push({ todo: a.todo });
        });
        return r;
    }(data);

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

问题解决方案(它会覆盖同一周和白天的待办事项!):

&#13;
&#13;
var data = [{ week: 1, day: 1, todo: "eq1" }, { week: 1, day: 3, todo: "eq2" }, { week: 4, day: 6, todo: "eq3" }, { week: 4, day: 7, todo: "eq4" }],
    object = function (data) {
        var r = {};
        data.forEach(function (a) {
            r[a.week] = r[a.week] || {};
            r[a.week][a.day] = { todo: a.todo };
        });
        return r;
    }(data);

document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

@Sergey部分正确。您将无法获得与存储在数组中相同的输出,其他值将设置为null。另外,您应该使用Object代替。

注意 这只是用于演示目的的示例代码,因此我刚检查了resultObj的可用性

&#13;
&#13;
var data = [
  { week: 1, day: 1, todo: "eq1" },
  { week: 1, day: 3, todo: "eq2" },
  { week: 4, day: 6, todo: "eq3" },
  { week: 4, day: 7, todo: "eq4" },
];

var resultObj = {};
var resultArr = [];

data.forEach(function(item) {
  if (!resultObj[item.week]){
    resultObj[item.week] = {};
    resultArr[item.week] = {};
    }

  if(!resultObj[item.week][item.day]){
    resultObj[item.week][item.day] = {"todo": item.todo}
    resultArr[item.week][item.day] = {"todo": item.todo}
  }
});

document.write("Object:<br/> <pre>" + JSON.stringify(resultObj, 0,4) + "</pre>");
document.write("Array: <br/> <pre>" + JSON.stringify(resultArr, 0,4) + "</pre>");
&#13;
&#13;
&#13;