【发布时间】:2019-11-18 21:50:04
【问题描述】:
我有这样的 JSON:
[
{
"PropertiesGroup1": {
"Size": "Big",
"Color": "Red"
},
"PropertiesGroup2": {
"City": "Berlin"
},
"PropertiesGroup3": {
"Price": "300$",
"Rating": "5",
"In stock": "Yes"
}
},
{
"PropertiesGroup1": {
"Size": "Medium",
"Color": "Blue",
"Weight" : "35"
},
"PropertiesGroup2": {
"City": "London",
"Location": "Random"
},
"PropertiesGroup3": {
"Price": "250$",
"Rating": "3",
"In Stock": "None"
},
"PropertiesGroup4": {
"Name": "TV",
"Guarantee": "2 years",
"Credit": "Yes"
}
},
{
"PropertiesGroup1": {
"Size": "Small",
"Color": "Black",
"Weight" : "65",
"Height" : "130"
},
"PropertiesGroup2": {
"City": "Paris",
"Location": "Rue 105"
},
"PropertiesGroup3": {
"Price": "270$",
"Rating": "4",
"In Stock": "None"
},
"PropertiesGroup7": {
"Quantity": "4"
},
"PropertiesGroup5": {
"Type": "Banana",
"Seller": "James"
}
}
]
而我需要得到的是:
[
{
"PropertiesGroup1": {
"Size": "Big | Medium | Small",
"Color": "Red | Blue | Black",
"Weight": "35 | 65",
"Height": "130"
},
"PropertiesGroup2": {
"City": "Berlin | London | Paris",
"Location": "Random | Rue 105"
},
"PropertiesGroup3": {
"Price": "300$ | 250$",
"Rating": "5 | 3 | 4",
"In stock": "Yes | None"
},
"PropertiesGroup4": {
"Name": "TV",
"Guarantee": "2 years",
"Credit": "Yes"
},
"PropertiesGroup7": {
"Quantity": "4"
},
"PropertiesGroup5": {
"Type": "Banana",
"Seller": "James"
}
}
]
所以我需要获取所有可能的组、它们的属性和值。 我已经尝试过,但我卡住了..
任何帮助将不胜感激!
这是我已经尝试过的,但它似乎不起作用:
const fs = require('fs');
let obj = JSON.parse(fs.readFileSync('my.json', 'utf-8'));
let sortedObj = [];
let objectKeys = [];
let finalObject = {};
for (i = 0; i < obj.length; i++) {
objectKeys[i] = Object.keys(obj[i]);
}
objectKeysResult = objectKeys[0];
for (j = 1; j < objectKeys.length; j++) {
objectKeysResult = unite(objectKeysResult, objectKeys[j]);
}
const categories = [];
for (i = 0; i < objectKeysResult.length; i++) {
key = objectKeysResult[i];
categories[i] = [...new Set(obj.map(bill => bill[key]))]
sortedObj[objectKeysResult[i]] = categories[i];
}
let uniqueKeys = Object.keys(Object.assign({}, ...sortedObj[objectKeysResult[0]]));
let keys = Object.keys(sortedObj);
let uniqueValues = [];
let newObject = [];
for (k = 0; k < keys.length; k++) {
for (i = 0; i < uniqueKeys.length; i++) {
uniqueValues[i] = sortedObj[keys[k]].map(function(obj) {
return obj[uniqueKeys[i]];
})
uniqueValues[i] = uniqueValues[i].filter(function(element) {
return element !== undefined;
});
newObject[uniqueKeys[i]] = uniqueValues[i].filter(function(elem, index, self) {
return index === self.indexOf(elem);
});
combinedObject[k] = newObject;
}
console.log(newObject);
finalObject[keys[k]] = combinedObject[k];
}
console.log(finalObject);
function unite() {
return [].concat.apply([], arguments).filter(function(elem, index, self) {
return self.indexOf(elem) === index;
});
}
【问题讨论】:
-
请将所有相关部分添加到问题中。
-
您好!你到底是什么意思?
-
您拥有什么、做过什么以及想要什么 - 无需访问其他页面。
-
哦,由于 StackOverflow 限制,我无法将此添加到问题中
标签: javascript node.js