Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
Format object with some keys to array

It gets a specific result from my database which I have shown below:


const data = {
  short: 'en',
  element: {
    'dsdsea-22dada-2ffgd-xxada-eeee': { name: 'test name', comment: 'test comment' },
    'adad2a-dda13-dsdad-wwwwd-adaxx': { name: 'name 2' },
}

And I would like to apply a JavaScript operation to be able to get this result:

[
    {
        short: 'en',
        key: "dsdsea-22dada-2ffgd-xxada-eeee.name"
    value: "test name"
    },
    {
        short: 'en',
        key: "dsdsea-22dada-2ffgd-xxada-eeee.comment"
    value: "test comment"
    },
    {
        short: 'en',
        key: "adad2a-dda13-dsdad-wwwwd-adaxx.name"
    value: "name 2"
    }
]

I have tried using a combination of Object.entries and the map function, but I don't know how to deal with double keys in a single element object.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This may be one possible solution to achieve the desired objective.

It uses Object.entries(), .map(), .flatMap() and template literal using backtick `` characters.

Code Snippet

const getTransformedArray = obj => (
  Object.entries(obj.element)   // iterate over 'element' key-value pairs
  .flatMap(([k1, v1]) => (      // k1-v1 where v1 is object (with name, comment props)
    Object.entries(v1)          // iterate over v1's key-value pairs
    .map(([k2, v2]) => ({       // map each iteration
      short: obj.short,         // create the resulting object
      key: `${k1}.${k2}`,       // 'key' is created using k1, k2
      value: v2                 // 'value' is v2 as-is
    }))
  ))                            // '.flatMap' used above avoids nesting of arrays
);

const data = {
  short: 'en',
  element: {
    'dsdsea-22dada-2ffgd-xxada-eeee': { name: 'test name', comment: 'test comment' },
    'adad2a-dda13-dsdad-wwwwd-adaxx': { name: 'name 2' }
  }
};

console.log(getTransformedArray(data));

Explanation

Inline comments in the code-snippet above explain how the code works.

EDIT

Answer updated to use .flatMap() as has been highlighted by @pilchard.

about 4 years ago · Juan Pablo Isaza Relatório

0

You'll need two loops to iterate over each element and then each value of those elements.

Here using for...of loops on the Object.entries() of each, destructuring at each level to apply relevant names to each property, and then creating a compound key value using a template literal

const data = {
  short: 'en',
  element: {
    'dsdsea-22dada-2ffgd-xxada-eeee': { name: 'test name', comment: 'test comment' },
    'adad2a-dda13-dsdad-wwwwd-adaxx': { name: 'name 2' },
  }
}

const result = [];
for (const [key, element] of Object.entries(data.element)) {
  for (const [prop, value] of Object.entries(element)) {
    result.push({ short: data.short, key: `${key}.${prop}`, value })
  }
}

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

Use Object.keys() to get the keys in element, then map the returned array using the key to access each element object and thus getting the name. Here's the full code snippet:

const input = {
    short: 'en',
    element: {
        'dsdsea-22dada-2ffgd-xxada-eeee': { name: 'test name', comment: 'test comment' },
        'adad2a-dda13-dsdad-wwwwd-adaxx': { name: 'name 2' },
    },
};

function format(data = {}) {
    const { short = '', element = {} } = data;

    let result = Object.keys(element).map((key) => {
        return Object.values(element[key]).map((value) => ({ short, key, value }));
    });

    result = result.flat();

    return result;
}

const result = format(input);
console.log(result)

this prints:

[
    {
        "short": "en",
        "key": "dsdsea-22dada-2ffgd-xxada-eeee",
        "value": "test name"
    },
    {
        "short": "en",
        "key": "dsdsea-22dada-2ffgd-xxada-eeee",
        "value": "test comment"
    },
    {
        "short": "en",
        "key": "adad2a-dda13-dsdad-wwwwd-adaxx",
        "value": "name 2"
    }
]
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda