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

210
Visualizações
How to create a new array for each unique key in an array of objects

I have an array of objects like so:

originalArray = [
    { "16": { "id": 23, "data": "11",}, "17": { "id": 28, "data": "25",},..., "header": "Row 2","id": 6},
    { "16": { "id": 23, "data": "AA",}, "17": { "id": 28, "data": "!!",},..., "header": "Row 2","id": 6},
    .... 
]

Where each array item is an object and within each object are several key-value pairs. The key-value pairs (other than the last two items with keys header and id) come in the format

"number": {"id": x, "data" = "something"}

There can be multiple objects and multiple key-value pairs within the array and the keys are consistent between each object i.e., if there is a key in the first object, it exists in all objects within the array e.g., "16" and "17"

I wrote a method to get the data from that array like so:

    createArrays() {
        this.originalArray.forEach(row => {
            Object.entries(row).forEach(([key, value]) => {
                console.log(key, value['data'])
            })
        });
    }

This enables me to get the key and the associated data value in each object. For each key (other than the header and id), how can I create a new array and populate it with the value of that key?

Desired outcome based on originalArray:

gridData_16 = ["11", "25", ...]
gridData_17 = ["AA", "!!", ...]
....

Explanation: we get new arrays that start with gridData_ and the last part comes from the key in the originalArray. Each value in the array comes from the data value for each key with the same number. For example, in originalArray, we have key "16" and "data" that are equal to "11" and "25" for each object in the array so we populate gridData_16 = ["11", "25", ...]

I know I can create an array outside of Object.keys and just populate that single array with all of the data using a .push method. However, that isn't quite the right structure and I'm unsure of how to move forward:

    createArrays() {

        this.gridData = []

        this.originalArray.forEach(row => {
            Object.entries(row).forEach(([key, value]) => {
                this.gridData.push(value['data'])
            })
        });
    }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Here's an approach that uses reduce() with Object.entries() to create a result object that groups the data values by key:

const array = [
    {"16": {"id": 23, "data": "11"}, "17": {"id": 28, "data": "25"}, "header": "Row 2", "id": 6},
    {"16": {"id": 23, "data": "AA"}, "17": {"id": 28, "data": "!!"}, "header": "Row 2", "id": 6}
];

const result = array.reduce((a, v) => {
  Object.entries(v).forEach(([k, v]) => {
    if (k.match(/[0-9]+/)) {
      a[k] = a[k] || [];
      a[k].push(v.data);
    }
  });
  
  return a;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can create an object with desired properties and add the values there, then you can simply change it to array if you need it in that format

const originalArray = [
    { "16": { "id": 23, "data": "11",}, "17": { "id": 28, "data": "25",}, "header": "Row 2","id": 6},
    { "16": { "id": 23, "data": "AA",}, "17": { "id": 28, "data": "!!",}, "header": "Row 2","id": 6}
]

function createArrays(originalArray) {

    const gridData = {}
    originalArray.forEach(row => {
        Object.entries(row).forEach(([key, value]) => {
            if(value.data){
              gridData['gridData_' + key] =  gridData['gridData_' + key] || []
              gridData['gridData_' + key].push(value.data)
            }
        })
    });
    return gridData
}

console.log(createArrays(originalArray))

about 4 years ago · Juan Pablo Isaza Relatório

0

You can simply achieve this without much modifications in your existing code.

Live Demo :

// Input Array
let originalArray = [{
  "16": {
    "id": 23,
    "data": "11"
  },
  "17": {
    "id": 28,
    "data": "25"
  },
  "header": "Row 2",
  "id": 6
}, {
  "16": {
    "id": 23,
    "data": "AA"
  },
  "17": {
    "id": 28,
    "data": "!!"
  },
  "header": "Row 2",
  "id": 6
}];

// Declaring an empty object to assignt the result.
let obj = {};

// Iterating original array to access the object enteries and get the values.
originalArray.forEach(row => {
  Object.entries(row).forEach(([key, value]) => {
    if (!isNaN(key)) {
      if (!obj[key]) {
        obj[key] = [];
      }
      obj[key].push(value.data)
    }
  })
});

// Output
console.log(obj);

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