将多维对象数组转换为对象的一维数组Javascript

时间:2016-01-13 13:55:06

标签: javascript arrays foreach

我有一个多维的对象数组,对Angular的ng-repeat造成严重破坏,所以我想将它转换为一维数组。我尝试过使用forEach但未能这样做。当我在运行函数后尝试使用console.log(newData)时,它返回一个空数组。我做得太简单了,还是犯了一个愚蠢的错误?

//Sample data (allData):

var allData = [{
  "period": 4,
  "uploadDate": "2015-11-19T21:00:00.000Z",
  "section": [{
    "transferCode": 8675309,
    "details": [{
      "voucherNumber": [34, 22],
      "vendor": "jimmy",
      "description": "blah      ",
      "amount": "t        45,555.00"
    }]
  }]
}, {
  "period": 4,
  "uploadDate": "2015-11-19T21:00:00.000Z",
  "section": [{
    "transferCode": 45576543,
    "details": [{
      "voucherNumber": [22, 33],
      "vendor": "Jonson",
      "description": "trap music      ",
      "amount": "t        12,345.00"
    }]
  }]
}]

//code to push to new array:

var newData = [];

function newArray() {
  allData.forEach(function(top) {
    top.section.forEach(function(mid) {
      mid.details.forEach(function(low) {
        newData.push({
          vendor: low.vendor,
          voucherNumber: low.voucherNumber,
          description: low.description,
          amount: low.amount,
          transferCode: mid.transferCode,
          uploadDate: top.uploadDate,
          period: top.period
        })
      })
    })
  })
  return newData;
}
newArray();
document.body.textContent = JSON.stringify(newData);

3 个答案:

答案 0 :(得分:1)

这可能有助于提升你的文字度......注意容器数组被跳过(例如"部分"和"详细信息")

// Helper functions
function isArray(obj) {return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) === '[object Array]';}
function isNumber(val) { return Object.prototype.toString.call(val) === '[object Number]' && isFinite(val);}


// Flatten object
function flatten(arg, out) {
    out = out || {};
    for (var prop in arg) {
        var val = arg[prop];

        if (isArray(val)) {
            for (var i = 0; i < val.length; i++) {

                // introspect if the array is just an array of numbers
                var valin = val[i];
                if (isArray(val) && isNumber(valin)) {

                    // just set to the number array and move along.
                    out[prop] = val;
                    break;
                } else {
                    flatten(valin, out);
                }
            }

        // continue looking deeper
        } else if (typeof val == "object") {
            flatten(val, out); 

        // get the value
        } else {
            out[prop] = val; 
        }
    }
    return out;
}


// Put each flattened object into a new data array
var data = [];
for (var i = 0; i < allData.length; i++) {
    data.push(flatten(allData[i]));
}

console.log(JSON.stringify(data));

答案 1 :(得分:1)

我不确定,您提供的解决方案是您想要的,因此这里是对数据的解释以及如何构建冗余数据集。

这是我更改代码的部分:

class MyController extends Controller {
    public function myAction(){
        $cortina = new Cortina();
        $cortina->something = "Some text";

        $em = $this->getDoctrine()->getManager();
        $em->persist($cortina);
        $em->flush();

        return $this->redirectToRoute('frontend_carrodecompras', array(
            'id' => $cortina->getId()
        );
    }
}
  

"details": [{ "voucherNumber": [34, 22, 23], "vendor": ["jimmy", "sam", "jones"], "description": ["blah", "blach", "bluch"], "amount": [45555, 232, 345346] }] 中的每个属性都包含一个长度相同的数组(希望如此)。我假设,每个索引都属于一个,如details

     

它的代码部分在34, jimmy, blah, 45555中查找键,然后查找每个属性数组的长度。然后它遍历长度和键并分配键/值对。收集完一个索引的所有值后,该对象将被推送到结果数组。

details

答案 2 :(得分:0)

好的,让它使用一些有用的建议,并采取一些不同的方向:

var allData = [{
  "period": 4,
  "uploadDate": "2015-11-19T21:00:00.000Z",
  "section": [{
    "transferCode": 8675309,
    "details": [{
      "voucherNumber": [34, 22, 23],
      "vendor": ["jimmy", "sam", "jones"],
      "description": ["blah", "blach", "bluch"],
      "amount": [45555, 232, 345346]
    }]
  }]
},
{
  "period": 4,
  "uploadDate": "2015-11-19T21:00:00.000Z",
  "section": [{
    "transferCode": 45576543,
    "details": [{
      "voucherNumber": [22, 33],
      "vendor": ["Jonson", "ronson"],
      "description": ["trap music", "jesus"],
      "amount": [12345, 23234]
    }]
  }]
}];

var newData = [];

function newArray() {
  allData.forEach(function(top) {
    top.section.forEach(function(mid) {
      mid.details.forEach(function(low) {
        low.vendor.forEach(function(vend){
            low.voucherNumber.forEach(function(vouch) {
                low.description.forEach(function(desc) {
                    low.amount.forEach(function(amt) {
                        newData.push({
                            vendor: vend.vendor,
                            voucherNumber: vouch.voucherNumber,
                            description: desc.description,
                            amount: amt.amount,
                            transferCode: mid.transferCode,
                            uploadDate: top.uploadDate,
                            period: top.period
                        });
                    });
                });
            });
        });
      });
    });
  });
  return newData;
}
newArray();
document.body.textContent = JSON.stringify(newData);
// var test = JSON.stringify(newData);
// console.log(test);