find keys from dynamiclly generated array object
Clash Royale CLAN TAG#URR8PPP
find keys from dynamiclly generated array object
I have a code which generates an array object like this
[
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 43323,
,
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 213,
"part@18%": 140.04,
"part@12%": 140.04,
"part@9%": 140.04,
"labour@18%": 140.04,
"offer@12%": 140.04,
"offer@9%": 140.04,
,
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 213,
,
"invoiceNumber": "INV-056",
"invoiceDate": "2018-06-19",
"jobCardNumber": "JC-018",
"tax": 213,
"part@9%": 140.04,
"labour@18%": 140.04,
"offer@12%": 140.04,
]
the part@, labour@ and offer@ keys are dynamic. I want all the keys from the array object.
the result i want is
[
'invoiceNumber',
'invoiceDate',
'jobCardNumber',
'tax',
'part@18%',
'part@12%',
'part@9%',
'labour@18%',
'offer@12%',
'offer@9%'
]
@jmargolisvt it will return [ '0', '1', '2', '3' ] i want
['invoiceNumber','invoiceDate','jobCardNumber','tax','part@18%','part@12%','part@9%','labour@18%','offer@12%','offer@9%']
– rahul prajapati
Aug 10 at 13:24
['invoiceNumber','invoiceDate','jobCardNumber','tax','part@18%','part@12%','part@9%','labour@18%','offer@12%','offer@9%']
Object.keys()
will give you the keys of any object. Map the array with object.keys, flatten the result and then filter out the uniques. Just simple array operations. This should be trivial once you know Object.keys()
. You only got [0,1,2,3] because you Object.key'ed the array instead of the objects inside the array.– Shilly
Aug 10 at 13:40
Object.keys()
Object.keys()
Are you saying you want a distinct list of all the keys which occur, no matter which object they occur in, or how many times they occur?
– ADyson
Aug 10 at 13:40
@ADyson yes exactly.
– rahul prajapati
Aug 13 at 4:58
1 Answer
1
You can loop through the objects with Array.prototype.reduce
and add their keys to the Set
:
Array.prototype.reduce
Set
var data=[invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:43323,invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:213,"part@18%":140.04,"part@12%":140.04,"part@9%":140.04,"labour@18%":140.04,"offer@12%":140.04,"offer@9%":140.04,invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:213,invoiceNumber:"INV-056",invoiceDate:"2018-06-19",jobCardNumber:"JC-018",tax:213,"part@9%":140.04,"labour@18%":140.04,"offer@12%":140.04];
var result = [...data.reduce((all, el) => (Object.keys(el).forEach(k => all.add(k)),all), new Set)];
console.log(result);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Object.keys(myObj)
– jmargolisvt
Aug 10 at 13:12