0

i have a array banks and I need to return one object with all the parameters described below

const banks = [{kod: 723,name: "bank",},{kod: 929,name: "bank2"}]

i tried to do it with

const lookup = banks.map(item => {
  return ({[item.kod]: item.name }) 
})

but it returns the result [ {723: "bank"}, {929: "bank2"} ]

how can i achieve this result {723: "bank",929: "bank2"}

Sined4ik
  • 119
  • 2
  • 11
  • You can't do it with `.map()` because the whole point is to *map* elements of an existing array into elements of a new array. You can however use `.reduce()` as in the posted answer. – Pointy Aug 08 '19 at 12:21

3 Answers3

4

You can use reduce instead

const banks = [{kod: 723,name: "bank",},{kod: 929,name: "bank2"}]

const lookup = banks.reduce((op,item) => {
  op[item.kod] =  item.name
  return op
},{})

console.log(lookup)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
2

You could take the result and assign all parts to a new object.

const
    banks = [{ kod: 723, name: "bank" }, { kod: 929, name: "bank2" }],
    lookup = Object.assign({}, ...banks.map(({ kod, name }) => ({ [kod]: name })));

console.log(lookup);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can use .reduce() with the spread syntax like so:

const banks = [{kod: 723,name: "bank",},{kod: 929,name: "bank2"}];

const res = banks.reduce((acc, {kod, name}) => ({...acc, [kod]: name}), {});
console.log(res);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64