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

240
Visualizações
JavaScript: Convert two-dimensional array with Map into Dictionary(nested Object)

I have a set of values in a two-dimensional array. I mapped an Object and made a new array. The first value key is a string and the second value currentTasks[key] is an array where each value has id, text, and date.

const newArray = Object.keys(currentTasks).map(function(key){
                return [key, currentTasks[key]];
            });

The newArray has a form like this…

['1', {id:'1', text: "Todo item #1", date: '2021-11-30'}]

What I want to do is to convert the newArray into the form of a Dictionary. I want to make the first value as a key, and the second value, in a HashMap form, as a value. How can I convert this form of the array into a hash map like a key-value pair?

{
        '1': {id:'1', text: "Todo item #1", date: '2021-11-30'},
        '2': {id:'2', text: "Todo item #2", date: '2021-12-12'},
        '3': {id:'3', text: "Todo item #3", date: '2021-11-29'},
        '4': {id:'4', text: "Todo item #4", date: '2021-12-03'},
}

I want to get a nested object array like this.

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

const testValues = [
        ['1', {id:'1', text: "Todo item #1", date: '2021-11-30'}],
        ['2', {id:'2', text: "Todo item #2", date: '2021-12-12'}],
        ['3', {id:'3', text: "Todo item #3", date: '2021-11-29'}],
        ['4', {id:'4', text: "Todo item #4", date: '2021-12-03'}]
];

const outputObject = {};
testValues.forEach(x => {
  outputObject[x[0]] = x[1];
});

console.log(testValues, outputObject);

about 4 years ago · Santiago Gelvez Relatório

0

If you are into brevity, I believe you are looking for the reduce array method.

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

You can provide an initial value, which in this case, is an object literal. You can then map over each sub array and provide the key: value pairs.

const array1 = [
        ['1', {id:'1', text: "Todo item #1", date: '2021-11-30'}],
        ['2', {id:'2', text: "Todo item #2", date: '2021-12-12'}],
        ['3', {id:'3', text: "Todo item #3", date: '2021-11-29'}],
        ['4', {id:'4', text: "Todo item #4", date: '2021-12-03'}]
];
const reducer = (previousValue, currentValue) => ({...previousValue, [currentValue[0]]: currentValue[1]});

// {1: {…}, 2: {…}, 3: {…}, 4: {…}}
console.log(array1.reduce(reducer, {}));

// as a one liner 
// array1.reduce((a, b) => ({...a, [b[0]]: b[1]}), {})

Or You could also use a Map

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

const array1 = [
        ['1', {id:'1', text: "Todo item #1", date: '2021-11-30'}],
        ['2', {id:'2', text: "Todo item #2", date: '2021-12-12'}],
        ['3', {id:'3', text: "Todo item #3", date: '2021-11-29'}],
        ['4', {id:'4', text: "Todo item #4", date: '2021-12-03'}]
];
const newMap = new Map()

array1.forEach(el => newMap.set(el[1], el[0]))



// 1: {…}, 2: {…}, 3: {…}, 4: {…}
newMap.forEach((key, value) => console.log(key, value))

about 4 years ago · Santiago Gelvez Relatório

0

I guess this is the output you are looking for?:

const values = [
        ['1', {id:'1', text: "Todo item #1", date: '2021-11-30'}],
        ['2', {id:'2', text: "Todo item #2", date: '2021-12-12'}],
        ['3', {id:'3', text: "Todo item #3", date: '2021-11-29'}],
        ['4', {id:'4', text: "Todo item #4", date: '2021-12-03'}]
]

const obj = {};

values.map(val => obj[val[0]] = val[1])

console.log(obj)

about 4 years ago · Santiago Gelvez 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