Home > OS >  reduce() object by arraykey is not using the first key javascript
reduce() object by arraykey is not using the first key javascript

Time:02-19

const cliente = {
    nome: "Andre",
    idade: 36,
    cpf: "123.456.789.10",
    email: "[email protected]"
}

const chaves = ["nome", "idade", "cpf", "email"];

const clienteString = chaves.reduce((acum, curr) => acum  = curr   ":"   cliente[curr]   ";")
 
console.log(clienteString);

the current output is: **nome**idade:36;cpf:123.456.789.10;email:[email protected];

the value of the key "nome:" is not being considered in the string

it should output this: nome:Andre;idade:36;cpf:123.456.789-10;email:[email protected];

what am i doing wrong?

CodePudding user response:

You should pass second reduce parameter to initialize it's accumulator:

A value to which previousValue is initialized the first time the callback is called. If initialValue is specified, that also causes currentValue to be initialized to the first value in the array. If initialValue is not specified, previousValue is initialized to the first value in the array, and currentValue is initialized to the second value in the array.

const cliente = {
    nome: "Andre",
    idade: 36,
    cpf: "123.456.789.10",
    email: "[email protected]"
}

const chaves = ["nome", "idade", "cpf", "email"];

const clienteString = chaves.reduce((acum, curr) => acum  = curr   ":"   cliente[curr]   ";", "")
 
console.log(clienteString);

CodePudding user response:

This is a simpler version that does what you want:

const cliente = {
  nome: "Andre",
  idade: 36,
  cpf: "123.456.789.10",
  email: "[email protected]",
};

console.log(
  Object.entries(cliente)
    .map(([key, value]) => `${key}:${value};`)
    .join("")
);

Object.entries returns an array of [key, value]. Then we map over that and turn it into an array of "key:value;". Then we concatenate the array of "key:value;" into a string.

  • Related