Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:从对象数组创建二维数组_Javascript_Jquery_Node.js_Arrays - Fatal编程技术网

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

Javascript:从对象数组创建二维数组,javascript,jquery,node.js,arrays,Javascript,Jquery,Node.js,Arrays,我有以下对象数组,并希望从中得到一个2d数组。 到目前为止,我所尝试的: let arr = [ { "id": '1', "userId": '1', "postId": 1, "type": 'like' }, { "id": '2', "userId": '1', "postId":

我有以下对象数组,并希望从中得到一个2d数组。 到目前为止,我所尝试的:

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]
})
这将返回:

[
    ["like"], ["like"], ["like"], ["dislike"], ["dislike"]
]
这不是预期的结果,预期的结果是:

[
    ["like", "like"], // User 1
    ["like", "dislike", "dislike"] // User 2
]
具有
userId 1
的用户有两个喜欢,而具有
userId 2
的用户有一个喜欢和两个不喜欢

我在这里遗漏了什么。

您可以使用:

const-original=[
{
id:'1',
用户ID:'1',
职位:1,,
键入:“喜欢”
},
{
id:'2',
用户ID:'1',
职位:1,,
键入:“喜欢”
},
{
id:'3',
用户ID:'2',
职位:3,,
键入:“喜欢”
}
];
const newArray=original.reduce((数组,项)=>{
const index=parseInt(item.userId)-1;
数组[索引]=数组[索引]??[];
数组[index].push(item.type);
返回数组;
}, []);

log(newArray)向我们展示您已经尝试过的内容,我们将修复您的工作。但我们不是来编写代码的;)@标记我已经用我的解决方案更新了我的问题。谢谢你的回答,它不会创建2d数组btw@Grammer你能运行代码并让我知道它与你想要的输出有什么不同吗?是的,略有不同,请看问题,预期结果需要是一个2d数组,只有
like
loke
,由于只有两个
userId
userId 1
有两个喜欢和
userId 2
有1个喜欢和2个不喜欢,我在问题末尾提到了预期数组,再次感谢。在返回/预期数组中,喜欢需要1,不喜欢需要0。查看更新的问题,现在应该更有意义了