使用对象的组数组项将超过2个元素

时间:2017-08-11 10:05:34

标签: javascript arrays object

我找到了解决我试图解决的问题的解决方案here

唯一的区别是我的对象数组有2个以上的元素 想要的结果类似于解决方案,但包含所有元素

{
    "group": "one",
    "color": ["red", "green", "black"],
    "size": ["big"],
    "date": ["11/08/2018"]
}

所以我一直在重复.map()以显示我的所有价值观,但我觉得我不应该...... 有人可以帮助我,更简单,更好的选择吗?



var db = [{"Record":{"id":"26","cost_center":"15073 DC1 M8 - Filmatic","batch_no":"367746","item_code":"12583","description":"LF Fruited Guava (2x6)x15"}},{"Record":{"id":"29","cost_center":"15073 DC1 M8 - Filmatic","batch_no":"367749","item_code":"12583","description":"LF Fruited Guava (2x6)x15"}},{"Record":{"id":"36","cost_center":"15093 DC1 M10 - CornerPot Machi","batch_no":"367756","item_code":"12256","description":"PROMO CP LF SaltedCar w H"}}];

var myArray = [];
for (var i in db) {
    if (db.hasOwnProperty(i)) {
        myArray.push(db[i].Record);
    }
}

var res = myArray.reduce(function(res, elem) {
    if (res.indexOf(elem.cost_center) === -1) {
        res.push(elem.cost_center);
    }
    return res;
}, []).map(function(machine) {
    return {
        cost_center: machine,
        batch_no: myArray.filter(function(_el) {
            return _el.cost_center === machine;
        }).map(function(_el) { return _el.batch_no; }),
        item_code: myArray.filter(function(_el) {
            return _el.cost_center === machine;
        }).map(function(_el) { return _el.item_code; }),
        description: myArray.filter(function(_el) {
            return _el.cost_center === machine;
        }).map(function(_el) { return _el.description; })
    }
});

console.log(res);




1 个答案:

答案 0 :(得分:1)

对于以后添加的代码,您可以使用哈希表,在其中收集具有相同cost_center的所有对象,并使用另一个数组来收集属性的值,例如batch_no,{{ 1}}和item_code



description

var db = [{ Record: { id: "26", cost_center: "15073 DC1 M8 - Filmatic", batch_no: "367746", item_code: "12583", description: "LF Fruited Guava (2x6)x15" } }, { Record: { id: "29", cost_center: "15073 DC1 M8 - Filmatic", batch_no: "367749", item_code: "12583", description: "LF Fruited Guava (2x6)x15" } }, { Record: { id: "36", cost_center: "15093 DC1 M10 - CornerPot Machi", batch_no: "367756", item_code: "12256", description: "PROMO CP LF SaltedCar w H" } }],
    keys = ["batch_no", "item_code", "description"],
    hash = Object.create(null),
    result = [];

db.forEach(function (o) {
    if (!hash[o.Record.cost_center]) {
        hash[o.Record.cost_center] = { cost_center: o.Record.cost_center };
        keys.forEach(function (k) {
            hash[o.Record.cost_center][k] = [o.Record[k]];
        });
        result.push(hash[o.Record.cost_center]);
        return;
    }
    keys.forEach(function (k) {
        hash[o.Record.cost_center][k].push(o.Record[k]);
    });
});

console.log(result);