通过按一个公共元素分组来重新格式化对象数组

问题描述 投票:0回答:1

我有以下数组:

var a = [{ "box":"1", "product":"Pen", "color":"White" },
    { "box":"1", "product":"Pencil", "color":"Blue" },
    { "box":"1", "product":"Marker", "color":"Red" },
    { "box":"2", "product":"Paper", "color":"White"},
    { "box":"2", "product":"GlossPaper", "color":"Yello"},
    { "box":"3", "product":"Eraser", "color":"Pink"}];

我想将其重新格式化为:

a={"box":[{"number":"1", "contents":[{"product":"Pen", "color":"White"},
    {"product":"Pencil", "color":"Blue"},
    {"product":"Marker", "color":"Red" }]},
    {"number":"2", "contents":[{"product":"Paper", "color":"White"},
    {"product":"GlossPaper", "color":"Yellow"}]},
    {"number":"3", "contents":[{"product":"Eraser", "color":"Pink"}]}]};

我正在尝试减少并尝试:

a = a.reduce(function(x, e) {
    var estKey = (e['box']);
    (x[estKey] ? x[estKey] : (x[estKey] = null || [])).push(e);
    return x;
    }, {});

但这不会产生所需的格式。如您所知,我正在介绍新的房产编号和内容

javascript arrays object grouping reformatting
1个回答
0
投票
var a = [
    { "box": "1", "product": "Pen", "color": "White" },
    { "box": "1", "product": "Pencil", "color": "Blue" },
    { "box": "1", "product": "Marker", "color": "Red" },
    { "box": "2", "product": "Paper", "color": "White" },
    { "box": "2", "product": "GlossPaper", "color": "Yello" },
    { "box": "3", "product": "Eraser", "color": "Pink" }
];

// Reformatting the array
var result = {};
result.box = [];

// Helper function to find or create a box object
function findOrCreateBox(number) {
    var boxObj = result.box.find(box => box.number === number);
    if (!boxObj) {
        boxObj = { number: number, contents: [] };
        result.box.push(boxObj);
    }
    return boxObj;
}

// Iterating through the original array and reformatting
a.forEach(item => {
    var boxObj = findOrCreateBox(item.box);
    var contentObj = { product: item.product, color: item.color };
    boxObj.contents.push(contentObj);
});

console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.