简体   繁体   English

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

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

Using TypeScript使用 TypeScript

Below is an array of objects & I want to map this in to a new object as provided below.下面是一个对象数组,我想将 map 放入一个新的 object 中,如下所示。 (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.从上面的对象数组中,我想将 map 后的值作为重复获取值的数组。 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.但它覆盖了一些值。 ie, 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]
      : [] || [],
  }),
  {}
);

This simple piece of code will work very smoothly.这段简单的代码将非常顺利地工作。

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

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);

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:您的问题是,当 get 属性未定义时,您实际上想用第一个帖子而不是空的 object 来完成它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM