【问题标题】:how to restructure a array of arrays into a array of objects如何将数组数组重组为对象数组
【发布时间】:2015-06-10 14:22:57
【问题描述】:

我需要帮助构建一个新的 json 对象数组。我从一组数组开始。我需要以一组对象结束。 javascript 或 linq.js 将完美运行。谢谢

这就是我的开始

var needtoChangeThisArray = [
        [1558, 219561],
        [2520, 438218],
        [3482, 656874],
        [4444, 875531],
        [5406, 1094187]
];

这就是数组的结构方式

var needsToLookLikeThisArray = [
{
"name": "Arbor Vista - Arbor Custom Homes",
"subId": "10394",
"bldId": "8598"
}, {
"name": "Arbor Vista - DR Horton - (OR)",
"subId": "10394", "bldId": "8597"
}, {
"name": "Copper Canyon Estates - Brentwood Homes",
"subId": "9048",
"bldId": "16737"
}`enter code here`
];

所以我需要结束这个

var needToEndUpWithThisArray = [
{
"sqft": "1558",
"price": "219561"
}, {
"sqft": "2520",
"price": "438218"
}, {
"sqft": "3482",
"price": "656874"
 }, {
"sqft": "4444",
"price": "875531"
}, {
"sqft": "5406",
"price": "1094187"
}
];

【问题讨论】:

    标签: javascript arrays linq.js


    【解决方案1】:

    这就够了吗?

    needToEndUpWithThisArray = needtoChangeThisArray.map(function(a) {
      return {
        sqft: a[0],
        price: a[1]
      };
    });
    

    【讨论】:

      【解决方案2】:

      应该这样做:

      //Your starting array
      var needtoChangeThisArray = [
              [1558, 219561],
              [2520, 438218],
              [3482, 656874],
              [4444, 875531],
              [5406, 1094187]
      ];
      
      //declaring your new array
      var needToEndUpWithThisArray = new Array();
      
      //looping through all your values, could also go with ForEach
      for (var i = 0; i < needtoChangeThisArray.length; i++) {
          var t = needtoChangeThisArray[i];
          var tempArray = {sqft:t[0], price:t[1]};
          needToEndUpWithThisArray.push(tempArray); //stuff your new array with the values.
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-21
        • 2018-10-13
        相关资源
        最近更新 更多