首页 > 解决方案 > 将 json 对象嵌套到具有重复父详细信息的单个 json 对象中以构造 html 表

问题描述

这是一个嵌套的 json 文件,我正在尝试以可读格式排列它以显示在表格中

我尝试手动将所有键和值放入 for 循环中,但应该有一种优雅的方式来实现这一点,因此我达到了 SO。

实际的 JSON 是一个非常嵌套的 JSON,需要时间来执行 500k 行的数据

结果应该是增强的 JSON,父值也出现在子值中

var property = {
	"data": [{
		"ID": "123456",
		"name": "Coleridge st",
		"criteria": [
			{
				"type": "type1",
				"name": "name1",
				"value": "7",
				"properties": []
			},
			{
				"type": "type2",
				"name": "name2",
				"value": "6",
				"properties": [
					{
						"type": "MAX",
						"name": "one",
						"value": "100"
					}, {
						"type": "MIN",
						"name": "five",
						"value": "5"
					}

				]
			},
			{
				"type": "type3",
				"name": "name3",
				"value": "5",
				"properties": [{
					"type": "MAX1",
					"name": "one6",
					"value": "1006"
				}, {
					"type": "MIN2",
					"name": "five6",
					"value": "56"
				}]
			}
		]
	},
	{
		"ID": "456789",
		"name": "New Jersy",
		"criteria": [
			{
				"type": "type4",
				"name": "name4",
				"value": "6",
				"properties": [{
					"type": "MAX12",
					"name": "one12",
					"value": "10012"
				}, {
					"type": "MIN23",
					"name": "five12",
					"value": "532"
				}]
			}
		]
	}]
};

var output = [];
property.data.forEach(function (users) {

	var multirows = {
		id: users.ID,
		name: users.name,
	};

	for (var i = 0; i < users.criteria.length; i++) {
		var criterias = {
			type: users.criteria[i].type,
			name: users.criteria[i].name,
			value: users.criteria[i].value,
		}

		var mat_contacts_rows;
		if (!isEmpty(users.criteria[i].properties)) {
			for (var j = 0; j < users.criteria[i].properties.length; j++) {
				var property = {
					type: users.criteria[i].properties[j].type,
					name: users.criteria[i].properties[j].name,
					value: users.criteria[i].properties[j].value
				};

				mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
				output.push(mat_contacts_rows);
			}
		} else {
			var property = [];
			mat_contacts_rows = { ...multirows, ...{ criteria: criterias }, ...{ properties: property } };
			output.push(mat_contacts_rows);
		}
	}
});

console.log(JSON.stringify(output, undefined, 2))


function isEmpty(obj) {
	for (var key in obj) {
		if (obj.hasOwnProperty(key))
			return false;
	}
	return true;
}

标签: javascriptjsondictionaryfilterreduce

解决方案


我认为这对你来说可能是一个很好的练习,不回答你的问题,而是给你一些提示。你应该首先看看:Lodash wish 有一堆有用的方法来帮助你做你想做的事情。在第二次你应该避免使用.forEachorfor循环并尝试使用Array.prototype.mapArray.prototype.reduce


推荐阅读