如何将一个数组值再次映射到另一个数组以产生结果

时间:2018-11-14 12:00:21

标签: javascript arrays json

假设有两个数组

Array 1是我的Firebase Objects JSON数组,如下所示:

"players" : [
       {"name" : "YB", 
        "Team" : "Industry",
        "id": 1, 
        "position": "forward",
       {"name" : "Harry",
        "Team" : "Industry", 
        "id": 2, 
        "position": "defender",
        {"name" : "Honey",
        "Team" : "Industry", 
        "id": 3, 
        "position": "defender",
        {"name" : "abel",
        "Team" : "Industry", 
        "id": 4, 
        "position": "defender",
        {"name" : "Shaka",
        "Team" : "Industry", 
        "id": 5, 
        "position": "defender",
        {"name" : "ben",
        "Team" : "Industry", 
        "id": 6, 
        "position": "defender",
        {"name" : "randy",
        "Team" : "Industry", 
        "id": 7, 
        "position": "defender",
        {"name" : "john",
        "Team" : "Industry", 
        "id":8 , 
        "position": "defender"
         }
       ]

数组2为

[1,2,5,4,8,6]

有没有一种方法可以遍历array 1,特别是对象属性id,以搜索array 2的值,然后仅生成具有以下内容的对象的结果数组: id 1,2,5,4,8,6(即,只有具有id属性值与array 2中的值相对应的对象的数组)

我对javascript / firebase云功能很陌生,想知道如何实现。我在下面尝试了映射功能:

var produce = array1.reduce (function(acc,next) {acc [next.id] = next; retrun acc;}, {});

var combine = array1.map(function(num){return produce[num];});

但是它一直返回错误消息a rray1.map is not a function。必须使用地图function.

来实现此目标的更简单方法

2 个答案:

答案 0 :(得分:2)

您可以使用.filter()来过滤记录,并使用id在第二个数组中检查.includes()

let data = [
  {"name" : "YB",    "Team" : "Industry", "id": 1, "position": "forward"},
  {"name" : "Harry", "Team" : "Industry", "id": 2, "position": "defender"},
  {"name" : "Honey", "Team" : "Industry", "id": 3, "position": "defender"},
  {"name" : "abel",  "Team" : "Industry", "id": 4, "position": "defender"},
  {"name" : "Shaka", "Team" : "Industry", "id": 5, "position": "defender"},
  {"name" : "ben",   "Team" : "Industry", "id": 6, "position": "defender"},
  {"name" : "randy", "Team" : "Industry", "id": 7, "position": "defender"},
  {"name" : "john",  "Team" : "Industry", "id": 8, "position": "defender"}
];

let matchIds = [1, 2, 5, 4, 8, 6];

let result = data.filter(({ id }) => matchIds.includes(id));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

从错误中可以推断出您要映射的变量不是数组。
假设firebase响应具有以下格式:

var result = {"players":[
                           {"name" : "YB","Team" : "Industry", 
                            "id":1,"position":"forward"},
                           {"name" : "Harry","Team" : "Industry", 
                            "id": 2,"position": "defender"}
                          ]
              }

然后,让第二个数组如下:

  var array2 = [1,2,5,4,8,6];

因此,“结果”变量实际上是此处的对象,而不是数组。在这种情况下,我们可以尝试执行以下操作,以防止出现问题中提到的错误:

var finalResult = result.players.filter (function(player) {
                  return array2.indexOf(player.id) > -1;
              });