Tengo datos como este:
data = [ { "emp_id": 1, "hashtag_id": [ 1, 3, 3, 4, 2, 2, 1, 1 ] }, { "emp_id": 2, "hashtag_id": [ 1, 1 ] }, { "emp_id": 3, "hashtag_id": [ 3, 1 ] }, { "emp_id": 4, "hashtag_id": [ 1, 3, 4 ] }, { "emp_id": 5, "hashtag_id": 1 }, { "emp_id": 6, "hashtag_id": [ 1, 4 ] } ] Quiero eliminar el valor duplicado en hashtag_id si existe.
esto es lo que esperaba:
data = [ { "emp_id": 1, "hashtag_id": [ 1, 3, 4, 2, ] }, { "emp_id": 2, "hashtag_id": [ 1 ] }, { "emp_id": 3, "hashtag_id": [ 3, 1 ] }, { "emp_id": 4, "hashtag_id": [ 1, 3, 4 ] }, { "emp_id": 5, "hashtag_id": 1 }, { "emp_id": 6, "hashtag_id": [ 1, 4 ] } ]Estaba intentando con esto:
data = data.map(item => { item.hashtag_id = [...new Set(item.hashtag_id)] return item })Pero obtuve un error:
"number 1 is not iterable (cannot read property Symbol(Symbol.iterator))"Qué hay de malo con eso ?
Dígame si necesita más información para resolver ese problema si aún no es suficiente.
En el elemento anterior al último, hashtag_id es un número en lugar de una matriz de números. Dado que un número no es iterable, no puede convertirlo en un conjunto que provoque el error.
Para tener en cuenta la posibilidad de que hashtag_id sea un número, haga lo siguiente:
data = data.map((item) => { item.hashtag_id = Array.isArray(item.hashtag_id) ? [...new Set(item.hashtag_id)] : item.hashtag_id; return item; })