如何使用JavaScript将对象数组转换为给定格式

时间:2016-03-18 14:36:37

标签: javascript

我需要使用JavaScript格式化数据数组。我使用以下数据:

var response = [{
      day_id:1,
      day_name:"Monday",
      subcat_id:"2",
      cat_id:"1",
      comment:"hii"
}, {
      day_id:1,
      day_name:"Monday",
      subcat_id:"1",
      cat_id:"2",
      comment:"hello"
}
 {
      day_id:2,
      day_name:"Tuesday",
      subcat_id:"3",
      cat_id:"2",
      comment:"hii"
}]

...我需要将其转换为以下格式

var responseNew = {
      data: [{
        day_name: "Monday",
        day_id:1
        answers:[{
          cat_id:1,
          subcat_id:1,
          comment:'hii'
        },{
          cat_id:1,
          subcat_id:2,
          comment:'hello'
        }]
      }, {
        day_name: "Tuesday",
        day_id:2
        answers:[{
          cat_id:3,
          subcat_id:2,
          comment:'hello'
        }]
      }, {
        day_name: "Wednesday"
         day_id:3
      }, {
        day_name: "Thursday"
         day_id:4
      }, {
        day_name: "Friday"
         day_id:5
      }, {
        day_name: "Saturday",
         day_id:6
      }, {
        day_name: "Sunday"
         day_id:7
      }]
    };

我想将第一个数组转换为第二个数组。一个条件是如果其他day_id不存在,它只是在上面给出的静态中设置日期名称和日期ID。

1 个答案:

答案 0 :(得分:1)

使用下划线按day_id分组,然后使用map渲染您想要的对象



  var response = [{
    day_id: 1,
    day_name: "Monday",
    subcat_id: "2",
    cat_id: "1",
    comment: "hii"
  }, {
    day_id: 1,
    day_name: "Monday",
    subcat_id: "1",
    cat_id: "2",
    comment: "hello"
  }, {
    day_id: 2,
    day_name: "Tuesday",
    subcat_id: "3",
    cat_id: "2",
    comment: "hii"
  }];


  var responseNew = _.chain(response)
    .groupBy("day_id")
    .map(function(obj) {
      return {
        day_name: obj[0].day_name,
        day_id: obj[0].day_id,
        answers: obj.map(function(o) {
          return {
            cat_id: o.cat_id,
            subcat_id: o.subcat_id,
            comment: o.comment
          }
        })
      };
    });
console.log(responseNew);

$("#myPre").html(JSON.stringify(responseNew, null, 4));

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="myPre"></pre>
&#13;
&#13;
&#13;