-1

What's the easiest way to get object keys from array of objects. Ex.

var obj = [{"foo": 1, "bar": 2}, {"foo": 10, "bar": 20, "baz": 30}]
// ['foo', 'bar', 'baz']
bobharley
  • 662
  • 3
  • 17
  • What do you want? A merged array of keys or all keys? – nilobarp Oct 19 '17 at 03:35
  • var obj = [{"foo": 1, "bar": 2}, {"foo": 10, "bar": 20, "baz": 30}]; var checkKeys = function () { var KeysArr=[]; obj.forEach(function (item) { var keys = Object.keys(item); keys.forEach(function (key) { if(KeysArr.indexOf(key)==-1) { KeysArr.push(key); }; }); }); return KeysArr; }; console.log(checkKeys()); – Pawan sasanka Oct 19 '17 at 05:21
  • all unique, keys – bobharley Oct 19 '17 at 05:50

1 Answers1

1

You can map everything to a single array with reduce:

obj.reduce((acc, curr) => acc.concact(Object.keys(curr)), [])

This gives you:

['foo', 'bar', 'foo', 'bar', 'baz']
  • Thanks! To remove duplicates, I did: `data.reduce((acc, curr) => acc.concat(Object.keys(curr)), []).filter(( item, index, inputArray ) => inputArray.indexOf(item) == index)` – bobharley Oct 19 '17 at 06:14
  • @HarleyDelaCruz you can also use `[...new Set(data)]` where `data` is the name of your array. – Hassan Imam Oct 19 '17 at 06:33