I need to obtain an array like this
[
"CD_DIRECAO",
"DT_INI_DIRECAO",
"CD_DEPT",
"DT_INI_DEPT"
]
from this array of objects
[
{
"CD_DIRECAO": "400"
},
{
"DT_INI_DIRECAO": "1900-01-01"
},
{
"CD_DEPT": "370"
},
{
"DT_INI_DEPT": "1900-01-01"
}
]
You can use map()
and Object.keys
methods with spread syntax ...
.
const data = [{"CD_DIRECAO":"400"},{"DT_INI_DIRECAO":"1900-01-01"},{"CD_DEPT":"370"},{"DT_INI_DEPT":"1900-01-01"}] const result = [].concat(...data.map(Object.keys)) console.log(result)
With ES6 you can use Object#assign and spread to merge the objects, and then get the keys using Object#keys:
const arr = [{"CD_DIRECAO":"400"},{"DT_INI_DIRECAO":"1900-01-01"},{"CD_DEPT":"370"},{"DT_INI_DEPT":"1900-01-01"}]; const obj = Object.keys(Object.assign({}, ...arr)); console.log(obj);
This might look a bit hacky but it gives the right output
const data = [
{
"CD_DIRECAO": "400"
},
{
"DT_INI_DIRECAO": "1900-01-01"
},
{
"CD_DEPT": "370"
},
{
"DT_INI_DEPT": "1900-01-01"
}
];
const newData = data.map(item => _.keys(item)).map(item => item[0]);
console.log(newData);
This will give the output as [ 'CD_DIRECAO', 'DT_INI_DIRECAO', 'CD_DEPT', 'DT_INI_DEPT' ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.