无法对对象数组中的键和值进行排序

时间:2019-07-09 10:47:14

标签: javascript node.js

我有这样的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;
  });
}

1 个答案:

答案 0 :(得分:1)

您可以从对象中获取键,并从内部对象中获取键和值,然后通过收集值来创建新对象。

顺便说一句,密钥需要具有相同的分组值,例如'In Stock''In stock'

const
    getUnique = (...v) => Array.from(new Set(v)),
    SEPARATOR = ' | ';

var data = [{ 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" } }],
    result = data.reduce((r, o) => {
        Object.entries(o).forEach(([k, p]) => {
            r[k] = r[k] || {};
            Object
                .entries(p)
                .forEach(([l, v]) => r[k][l] = r[k][l]
                    ? getUnique(...r[k][l].split(SEPARATOR), v).join(SEPARATOR)
                    : v);
        });
        return r;
    }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }