js数组中的对象去重

要去重的数组:

[
    {
        "itemId": 1,
        "itemName": "整体",
        "libraryId": 3,
        "objectName": "车行道",
        "categoryName": "道路感观质量评价",
        "categoryId": 1,
        "objectId": 1
    },
    {
        "itemId": 2,
        "itemName": "纸塑、果皮等 ",
        "libraryId": 3,
        "objectName": "车行道",
        "categoryName": "密度质量检测",
        "categoryId": 2,
        "objectId": 3
    },
    {
        "itemId": 3,
        "itemName": "纸塑、果皮等",
        "libraryId": 3,
        "objectName": "人行道",
        "categoryName": "密度质量检测",
        "categoryId": 2,
        "objectId": 4
    },
    {
        "itemId": 4,
        "itemName": "整体",
        "libraryId": 3,
        "objectName": "人行道",
        "categoryName": "道路感观质量评价",
        "categoryId": 1,
        "objectId": 2
    },
    {
        "itemId": 10,
        "itemName": "路面本色",
        "libraryId": 3,
        "objectName": "车行道",
        "categoryName": "道路感观质量评价",
        "categoryId": 1,
        "objectId": 1
    },
    {
        "itemId": 11,
        "itemName": "路面本色",
        "libraryId": 3,
        "objectName": "人行道",
        "categoryName": "道路感观质量评价",
        "categoryId": 1,
        "objectId": 2
    }
]

比如我们要去重objectId或者categoryId,只需要传入数组和id名称即可:

/**
 * 传入数组,和去重数组中的对象属性名
 * @param arr
 * @param id 字符串类型,对象属性名
 * @returns {*}
 */
export function removeDuplicateObj(arr,id) {
  let obj = {};
  arr = arr.reduce((newArr, next) => {
    obj[next[id]] ? "" : (obj[next[id]] = true && newArr.push(next));
    return newArr;
  }, []);
  return arr;
}

去重后:

[
    {
        "itemId": 1,
        "itemName": "整体",
        "libraryId": 3,
        "objectName": "车行道",
        "categoryName": "道路感观质量评价",
        "categoryId": 1,
        "objectId": 1
    },
    {
        "itemId": 4,
        "itemName": "整体",
        "libraryId": 3,
        "objectName": "人行道",
        "categoryName": "道路感观质量评价",
        "categoryId": 1,
        "objectId": 2
    }
]

你可能感兴趣的:(前端,javascript)