简体   繁体   中英

Flatten an array in json to the object level

I have the following json array, and would like to massage the "Year" array at its object level. In other words take the Year array an have each element as an element of the parent object. Any ideas?

[

  {
    "Expnses": [],
    "Earnings": [
      {
        "ID": "1234",
        "Total": "1000",
        "Year": [
          {
            "yr": 1,
            "amt": 100
          },
          {
            "yr": 2,
            "amt": 5500
          }
        ]
      }
    ]
  }
]

Expected:

[
  {
    "Expnses": [],
    "Earnings": [
      {
        "ID": "1234",
        "Total": "1000",
        "Year1": 100,
        "Year2": 5500
      }
    ]
  }
]

Not the prettiest solution but you can use the following code, are you able to control how the the json object returned is formatted?

var jsonArray = [{
    "Expnses": [],
    "Earnings": [{
        "ID": "1234",
        "Total": "1000",
        "Year": [{
            "yr": 1,
            "amt": 100
          },{
            "yr": 2,
            "amt": 5500
        }]
    }]
}];

jsonArray[0]["Earnings"][0]["Year"].forEach(function(element, index) {
    jsonArray[0]["Earnings"][0]["Year" + element["yr"]] = element["amt"];
});

delete jsonArray[0]["Earnings"][0]["Year"];

You could use a dynamic approach for all keys and for any length.

 var data = [{ Expnses: [], Earnings: [{ ID: "1234", Total: "1000", Year: [{ yr: 1, amt: 100 }, { yr: 2, amt: 5500 }] }] }], result = data.map(function (o) { var r = {}; Object.keys(o).forEach(function (k) { r[k] = o[k].map(function (a) { var p = { ID: a.ID, Total: a.Total }; a.Year.forEach(function (b) { p['Year' + b.yr] = b.amt; }); return p; }); }); return r; }); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

 var array = [{ "Expnses": [], "Earnings": [{ "ID": "1234", "Total": "1000", "Year": [{ "yr": 1, "amt": 100 }, { "yr": 2, "amt": 5500 } ] } ] } ]; /** * Flattens Earnings.Year array objects into properties ... * @param {object} source - the object to process. * @param {boolean?} cloneSource - if procces has to be exectued on the clone of the object. * @param {boolean?} deleteArray - if the array has to be deleted. * @param {object} processed source object is returned .. */ function flattenYear(source, cloneSource, deleteArray) { var _source = !!cloneSource ? JSON.parse(JSON.stringify(source)) : source; if (!_source.Earnings) { return _source; } _source.Earnings.forEach(earning => { if (!earning.Year) { return; } earning.Year.forEach(year => { earning['Year' + year.yr] = year.amt; }); if (!!deleteArray) { delete earning.Year; } }); return _source; } /* flatten with deep clone and delete array ... */ var z = array.map(m => flattenYear(m, true, true)); console.log('z[0].Earnings[0]', z[0].Earnings[0]); console.log('Was source array modified ? : ', JSON.stringify(z) == JSON.stringify(array)); /* flatten and delete array ... */ var y = array.map(m => flattenYear(m, false, false)); console.log('\\n','y[0].Earnings[0]', y[0].Earnings[0]); console.log('Was source array modified ? : ', JSON.stringify(y) == JSON.stringify(array)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM