将json中的数组展平到对象级别

时间:2017-03-13 20:01:09

标签: javascript arrays lodash

我有以下json数组,并希望按摩"年"数组在其对象级别。换句话说,取Year数组将每个元素作为父对象的元素。有什么想法吗?

[

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

预期:

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

3 个答案:

答案 0 :(得分:0)

不是最漂亮的解决方案,但您可以使用以下代码,您是否能够控制返回的json对象的格式?

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"];

答案 1 :(得分:0)

您可以对所有键和任何长度使用动态方法。



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; }




答案 2 :(得分: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));