Take the value javaScript with the same attributes of the object

as long as the b1 attribute has the same value, throw the same later into the children array

let obj = [{"a1": "bbb", "b1": "jkk"}, {"a1": "ccc", "b1": "jkp"}, {"a1": "ddd", "b1": "jkk"}, {"a1": "eee", "b1": "jkk"},...];

//
[{
    "a1": "bbb",
    "b1": "jkk",
    children: [{
        "a1": "ddd",
        "b1": "jkk"
    },{
        "a1": "eee",
        "b1": "jkk"
    }],
}, {
    "a1": "ccc",
    "b1": "jkp"
}];
May.01,2021

let obj = [{'a1': 'bbb', 'b1': 'jkk'}, {'a1': 'ccc', 'b1': 'jkp'}, {'a1': 'ddd', 'b1': 'jkk'}, {'a1': 'eee', 'b1': 'jkk'}];

function dealObj(obj) {
    let keyIndex = {}, objItem, result = [], index;
    for (let i = 0; i < obj.length; iPP) {
        objItem = obj[i];
        if (undefined === keyIndex[objItem.b1]) {
            index = result.length;
            keyIndex[objItem.b1] = index;
            result.push(objItem);
        } else {
            index = keyIndex[objItem.b1];
            if (undefined === result[index].children) result[index].children = [];
            result[index].children.push(objItem);
        }
    }
    return result;
}

console.log(dealObj(obj));
Menu