简体   繁体   English

Javascript:从对象数组创建二维数组

[英]Javascript: Create 2 dimensional array from array of objects

I have the following array of objects and want to have a 2d array from it.我有以下对象数组,并希望从中获得一个二维数组。 What I have tried so far:到目前为止我已经尝试过:

let arr = [
  {
    "id": '1',
    "userId": '1',
    "postId": 1,
    "type": 'like'
  },
  {
    "id": '2',
    "userId": '1',
    "postId": 2,
    "type": 'like'
  },
  {
    "id": '3',
    "userId": '2',
    "postId": 3,
    "type": 'like'
  },
  {
    "id": '4',
    "userId": '2',
    "postId": 4,
    "type": 'dislike'
  },
  {
    "id": '5',
    "userId": '2',
    "postId": 1,
    "type": 'disklike'
  },
];

var newArr = arr.map(function(val, index){          
 return [val.type]
})

This returns:这将返回:

[
    ["like"], ["like"], ["like"], ["dislike"], ["dislike"]
]

Which is not the expected results, The expected results are:这不是预期的结果,预期的结果是:

[
    ["like", "like"], // User 1
    ["like", "dislike", "dislike"] // User 2
]

as user with userId 1 have two likes and user with userId 2 have one like and two dislikes.因为userId 1的用户有两个喜欢,而userId 2的用户有一个喜欢和两个不喜欢。

What am I missing here.我在这里想念什么。

You can use:您可以使用:

 const original = [ { id: '1', userId: '1', postId: 1, type: 'like' }, { id: '2', userId: '1', postId: 1, type: 'like' }, { id: '3', userId: '2', postId: 3, type: 'like' } ]; const newArray = original.reduce ((array, item) => { const index = parseInt(item.userId) - 1; array[index] = array[index]?? []; array[index].push(item.type); return array; }, []); console.log(newArray);

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

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