To deal with the problem of JSON data duplication in JS, take the same name field values as an array, and the different ones as an array.

topic description

the interface values obtained from the backend are dynamic, and the values of id and name are dynamic. The format of json is as follows, to give a simple example:

var arr = [
    {id:1,name:2},
    {id:2,name:13},
    {id:3,name:2},
    {id:10,name:2}
];

now, the final effect I need to get based on the same name is as follows:

arr1 = [{id:2,name:13}]
arr2 = [
    {id:1,name:2},
    {id:3,name:2},
    {id:10,name:2}
]

that means you need to split an array with different name; an array with the same name value;
ask your bosses to help you solve it?

Mar.09,2022

var arr = [
    {id:1,name:2},
    {id:2,name:13},
    {id:3,name:2},
    {id:10,name:2}
];
function f(arr) {
    var mp= {}
    var ret = []
    arr.forEach(item => {
        if (typeof mp[item.name] === 'number') {
            ret[mp[item.name]].push(item)
        } else {
            mp[item.name] = ret.length
            ret.push([item])
        }
    })
    return ret
}
console.log(f(arr))
Menu