1

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"
    }
]

4 Answers 4

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Cleanest answer.
1

With lodash you could use flatMap and keys:

let result = _.flatMap(data, _.keys);

Comments

1

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);

Comments

0

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' ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.