mx_code
mx_code

Reputation: 2517

How to map object values from one key of the same object for object keys with same values of the same object?

Using TypeScript

Below is an array of objects & I want to map this in to a new object as provided below . (see the expected result)

// input array
const getPostAPI = 
[
  {
    get: '1234',
    post: 'abcd',
  },
  {
    get: '3423',
    post: 'dfcv',
  },
  {
    get: '1234',
    post: 'iucv',
  },
  {
    get: '1234',
    post: 'oipl',
  },
  {
    get: '3423',
    post: 'ffgf',
  },
  {
    get: '4567',
    post: 'tyui',
  },
  ]

from the above array of objects I want to map the post values as an array for repeating get values. Below I've provided the exptected result.

// output object
const exptectedResult = {
  '1234': ['abcd',
    'iucv',
    'oipl',
    '1234',],
  '3423': ['dfcv',
    'ffgf'],
  '4567': ['tyui']
  }

Following is what I've tried. But it is overwriting some of the values. i.e., I'm not getting the exact number of elements in the array of corresponding get key. (it is one less than actual)

this.getPostMap = this.getPostAPI.reduce(
  (map, api) => ({
    ...map,
    [api.get]: map[api.get]
      ? [...map[api.get], api.post]
      : [] || [],
  }),
  {}
);

Upvotes: 1

Views: 848

Answers (3)

Daimellah Sofiane
Daimellah Sofiane

Reputation: 113

Your Problem is that when the get property is undefined, you actually want to fulfill it with the first post instead of an empty object :

this.getPostMap = this.getPostAPI.reduce(
  (map, api) => ({
    ...map,
    [api.get]: map[api.get]
      ? [...map[api.get], api.post]
      : [api.post],
  }),
  {}
);

Upvotes: 0

Klaycon
Klaycon

Reputation: 11080

That is quite a terrifying and unreadable block of code to do something that can be very simple. For example:

const getPostAPI = [{
    get: '1234',
    post: 'abcd',
  },
  {
    get: '3423',
    post: 'dfcv',
  },
  {
    get: '1234',
    post: 'iucv',
  },
  {
    get: '1234',
    post: 'oipl',
  },
  {
    get: '3423',
    post: 'ffgf',
  },
  {
    get: '4567',
    post: 'tyui',
  },
];

const expectedResult = getPostAPI.reduce((map, {get,post}) =>
  (map[get] = map[get] || []).push(post) && map,
{});

console.log(expectedResult);

Upvotes: 1

Omkar Kulkarni
Omkar Kulkarni

Reputation: 1215

This simple piece of code will work very smoothly.

getPostAPI.reduce((acc, el)=>{
    (acc[el.get] = acc[el.get] || []).push(el.post)
    return acc
}, {})

Upvotes: 1

Related Questions