-1

I have this array of objects:

[
  { bankName: { id: 1, name: 'SANTANDER' }, totalClients: 12 },
  { bankName: { id: 3, name: 'ESTADO' }, totalClients: 9 },
  { bankName: { id: 2, name: 'CHILE' }, totalClients: 8 }
]

how can i get this object?

{
  'SANTANDER': 12,
  'ESTADO': 9,
  'CHILE': 8
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Why would you want to do that? And also share the code chunk that you made. – Raky Jul 04 '21 at 02:38
  • having conversion problems, i have no code yet... – Nicolás Poblete Añsñfk Jul 04 '21 at 02:41
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Jul 04 '21 at 04:01

1 Answers1

4

You can use reduce to get the desired result.

const arr = [
  { bankName: { id: 1, name: "SANTANDER" }, totalClients: 12 },
  { bankName: { id: 3, name: "ESTADO" }, totalClients: 9 },
  { bankName: { id: 2, name: "CHILE" }, totalClients: 8 },
];

const result = arr.reduce((acc, curr) => {
  acc[curr.bankName.name] = curr.totalClients;
  return acc;
}, {});

console.log(result);

2)

const arr = [
  { bankName: { id: 1, name: "SANTANDER" }, totalClients: 12 },
  { bankName: { id: 3, name: "ESTADO" }, totalClients: 9 },
  { bankName: { id: 2, name: "CHILE" }, totalClients: 8 },
];

const result = arr.reduce((acc, { bankName: { name: key }, totalClients: value}) => {
    acc[key] = value;
    return acc;
  }, {});

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42