鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ 取對象屬性相同的value javaScript

取對象屬性相同的value javaScript

只要b1屬性值有相同的,就把后面相同的都扔進children數(shù)組里面去

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

//想要的最后結(jié)果
[{
    'a1': 'bbb',
    'b1': 'jkk',
    children: [{
        'a1': 'ddd',
        'b1': 'jkk'
    },{
        'a1': 'eee',
        'b1': 'jkk'
    }],
}, {
    'a1': 'ccc',
    'b1': 'jkp'
}];
回答
編輯回答
別傷我
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; i++) {
        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));
2017年6月10日 23:18