【问题标题】:Nested json object into single json objects with repeating parent details to construct html table将 json 对象嵌套到具有重复父详细信息的单个 json 对象中以构造 html 表
【发布时间】:2019-11-04 01:42:36
【问题描述】:

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

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

实际的 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;
}

【问题讨论】:

    标签: javascript json dictionary filter reduce


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多