JSON format to extract a value of the same property

[
{UID:"222",value:"111"},
{UID:"222",value:"103"},
{UID:"123",value:"302"},
{UID:"123",value:"031"}
]
改成[
{UID:"222",value:"111,103"},
{UID:"123",value:"302,031"}
]

function handle(arr) {
    var res = [],
        obj = {},
        index = 0;
    arr.forEach(val => {
        if (obj.hasOwnProperty(val.UID)) {
            res[obj[val.UID]].value = res[obj[val.UID]].value + ',' + val.value;
        } else {
            obj[val.UID] = index++;
            res.push({
                UID: val.UID,
                value: val.value
            });
        }
    });
    return res;
}
var arr = [{
    UID: "222",
    value: "111"
}, {
    UID: "222",
    value: "103"
}, {
    UID: "123",
    value: "302"
}, {
    UID: "123",
    value: "031"
}]
console.log(handle(arr))

Ideas:

1. Create a new storage array results

2. Create an empty object

When 3.for cycle, takes out a comparison with the object element, if this element is not repeated, it is put through the result array, while the contents of the element as an attribute of the object, and the value of 1, into to an object created in step 2.

Note: As to how the comparison, the original is removed from each array element, then to the object to access the property, if access to a value, then repeat.

This article is reproduced from segmengDefault and scripts House

Guess you like

Origin www.cnblogs.com/1212dsa/p/11425930.html