-1

With Javascript how can I get the id of each object in this kind of object:

array = [
    { active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'one' },
    { active: false, defaultTag:true, id: '507f191e810c19722de860ea', title: 'two' }
];

I need to fetch the id in order to check if the item already exists in the array whe a use intent to save the same object again.

Best regards Americo

Hrishi
  • 1,210
  • 1
  • 13
  • 25
Americo Perez
  • 95
  • 1
  • 4
  • 17
  • 2
    Please don't upload [images of code](https://meta.stackoverflow.com/a/285557/3082296). They can't be copied, aren't searchable for future readers and harder to read than text. Please post the actual code **as text** to create a [mcve]. – adiga Feb 27 '19 at 14:54
  • Possible duplicate of [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865) – adiga Feb 27 '19 at 14:55
  • That was a screenshot from the Firefox console, I will try to write the same as code – Americo Perez Feb 27 '19 at 16:14

2 Answers2

0

here you can get array of unique ids

 var unique = [],
 tmp, i = 0;
 while(i < array.length){
   unique.indexOf(tmp = array[i++].id) > -1 ? array.pop(i--) : unique.push(tmp)
 }
 console.log(unique);
Hrishi
  • 1,210
  • 1
  • 13
  • 25
0
  1. Gather all your items under one object using Array.reduce. This will filter out duplicates
  2. Use Object.values to get the values inside your object. The returned value is the filtered array

const array = [
    { active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'duplicateOne' },
    { active: false, defaultTag:true, id: '507f191e810c19729de860ea', title: 'one' },
    { active: false, defaultTag:true, id: '507f191e810c19722de860ea', title: 'two' }
];

const removeDupsById = arr => Object.values(
  arr.reduce((a, c) => ({...a, [c.id]: c}), {})
);

console.log(removeDupsById(array));
molamk
  • 4,076
  • 1
  • 13
  • 22