0

I have an array of object such that every element has unique objects. How can I make a list of all those unique elements? Eg

const obj = [
  {
    a: 'a',
    b: 'b',
  },
  {
    c: 'c',
    d: 'd',
  },
  {
    e: 'e',
    f: 'f',
  },
];

I want an array of keys - [a,b,c,d,e,f]

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • have you tries something? what does not work? – Nina Scholz Mar 04 '21 at 11:52
  • 1
    `Array.from(new Set(obj.map(i => Object.keys(i)))).flat()` – Dominik Matis Mar 04 '21 at 11:53
  • @DominikMatis that looks like a good answer. – evolutionxbox Mar 04 '21 at 11:55
  • [Get array of object's keys](https://stackoverflow.com/q/8763125) + [Merge/flatten an array of arrays](https://stackoverflow.com/q/10865025) + [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/q/1960473) – VLAZ Mar 04 '21 at 11:56
  • 1
    i am really surprised why this question gets upvotes. it is unclear what op is looking for, because of the same strings for key and value and op has not included some code which does not work. – Nina Scholz Mar 04 '21 at 12:03

3 Answers3

1

First of all you need to rotate your loop of array then you need to rotate your json loop.

const obj = [{
 a:'a',
 b:'b',   
},
{
 c:'c',
 d:'d',   
},
{
 e:'e',
 f:'f',   
}]
let keys = [];
for(let i= 0; i < obj.length; i++){
  for(let key in obj[i]){
    keys.push(key);
  }
}
console.log(keys);
Aman Gojariya
  • 1,289
  • 1
  • 9
  • 21
1

const obj = [{
 a:'a',
 b:'b',   
},
{
 c:'c',
 d:'d',   
},
{
 e:'e',
 f:'f',   
}]

const res = obj.map(a=> Object.values(a)).flat()

console.log(res)
ptothep
  • 415
  • 3
  • 10
-2
let array = []
obj.map((values, index) => {
    array = [...Object.keys(values), ...array]
})

try the above code and comment if any doubt

Vijay
  • 228
  • 3
  • 8