0

If the 'id' key is duplicated among the objects in the array, how to delete the object

I tried using filter, map, and set, but it doesn't work. It's not a one-dimensional array, so I don't know how to do it.

as-is

"category": {
    "key": 1,
    "order": 1,
    "list": [
        {
            "id": "12345",
            ...
        },
        {
            "id": "12345",
            ...
        },
        {
            "id": "67890",
            ...
        },
        
    ]
}

to-be

"category": {
    "key": 1,
    "order": 1,
    "list": [
        {
            "id": "12345",
            ...
        },
        {
            "id": "67890",
            ...
        },
        
    ]
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ddon
  • 185
  • 3
  • 4
  • 15
  • 1
    `obj.category.list = obj.category.list.filter((o,i,a) => a.findIndex(o2 => o2.id == o.id) == i)` – Nick Oct 17 '22 at 03:08

3 Answers3

1

A solution based on @Nick's comment

let data ={
"category": {
    "key": 1,
    "order": 1,
    "list": [
        {
            "id": "12345"
        },
        {
            "id": "12345"
        },
        {
            "id": "67890"
        },
        
    ]
}
}


let uniq = data.category.list.filter((o,i,a) => a.findIndex(o2 => o2.id == o.id) == i)
data.category.list = uniq
console.log(data)
flyingfox
  • 13,414
  • 3
  • 24
  • 39
1
  • We iterate over that list using reduce function, then we checked whether the key we are accessing is visited or not with keys parameter of reduce method, and if it's not visited then we just push that object to a filtered array and returning keys array to keep it updated.

const data = {
  "category": {
    "key": 1,
    "order": 1,
    "list": [{
        "id": "12345"
      },
      {
        "id": "12345"
      },
      {
        "id": "67890"
      },

    ]
  }
}
let filtered = [];

data.category.list.reduce((keys, currentObject) => {
  if (!keys.includes(currentObject.id)) { //checking if current oject id is present in keys or not
    // if not present than we will just push that object in 
    keys.push(currentObject.id);
    //getting filttered object
    filtered.push(currentObject);
  }
  return keys; //returning keys to update it
}, [])
data.category.list = filtered; //updating list
console.log(data);
Nexo
  • 2,125
  • 2
  • 10
  • 20
0

You can use a set to track if id

const category = [{
  "category": {
    "key": 1,
    "order": 1,
    "list": [{
        "id": "12345",
      },
      {
        "id": "12345",
      },
      {
        "id": "67890",
      },

    ]
  }
}]
const z = category.map(elem => {
  const set = new Set()
  return {
    ...elem,
    category: {
      ...elem.category,
      list: elem.category.list.reduce((acc, curr) => {
        if (!set.has(curr.id)) {
          set.add(curr.id);
          acc.push(curr)
        }
        return acc;
      }, [])
    }
  }
});
console.log(z)
brk
  • 48,835
  • 10
  • 56
  • 78