Javascript 如何在将用户id与仅保存用户id的第二个JSON匹配后从JSON对象获取用户名字符串

Javascript 如何在将用户id与仅保存用户id的第二个JSON匹配后从JSON对象获取用户名字符串,javascript,json,Javascript,Json,我尝试遍历两个不同的JSON对象 第一个保存的订单数据包含orderIduserId和productId,如下所示: [{ "orderId": 1, "userId": 1, "productId": 001 }, { "orderId": 2, "userId": 2, "productId": 001 }, { "orderId": 3, "userId": 2, "productId

我尝试遍历两个不同的JSON对象

第一个保存的订单数据包含
orderId
userId
productId
,如下所示:

[{  
    "orderId": 1, 
    "userId": 1,
    "productId": 001
  },
  {  
    "orderId": 2, 
    "userId": 2,
    "productId": 001
  },
  {  
    "orderId": 3, 
    "userId": 2,
    "productId": 002
  },
  {  
    "orderId": 4, 
    "userId": 2,
    "productId": 002
  },
  {  
    "orderId": 5, 
    "userId": 3,
    "productId": 003
  },
  {  
    "orderId": 6, 
    "userId": 1,
    "productId": 003
  },
  {  
    "orderId": 7, 
    "userId": 1,
    "productId": 003
  }

]
[{  
    "userId": 1,
    "name": "john", 
    "email": "john@gmail.com"
  },
  {  
    "userId": 2,
    "name": "mike", 
    "email": "mike@gmail.com"
  },
  {  
    "userId": 3,
    "name": "jane", 
    "email": "jane@gmail.com"
  }
]
第二个JSON保存用户数据,如下所示:

[{  
    "orderId": 1, 
    "userId": 1,
    "productId": 001
  },
  {  
    "orderId": 2, 
    "userId": 2,
    "productId": 001
  },
  {  
    "orderId": 3, 
    "userId": 2,
    "productId": 002
  },
  {  
    "orderId": 4, 
    "userId": 2,
    "productId": 002
  },
  {  
    "orderId": 5, 
    "userId": 3,
    "productId": 003
  },
  {  
    "orderId": 6, 
    "userId": 1,
    "productId": 003
  },
  {  
    "orderId": 7, 
    "userId": 1,
    "productId": 003
  }

]
[{  
    "userId": 1,
    "name": "john", 
    "email": "john@gmail.com"
  },
  {  
    "userId": 2,
    "name": "mike", 
    "email": "mike@gmail.com"
  },
  {  
    "userId": 3,
    "name": "jane", 
    "email": "jane@gmail.com"
  }
]
第三个JSON对象包含产品数据。包括以下内容以供参考:

[
  {  
    "productId": 001,
    "productName": "square"
  },
  {  
    "productId": 002,
    "productName": "triangle"
  },
  {  
    "productId": 003,
    "productName": "hexagon"
  }
]
我试图做的是比较USERS和ORDERS对象,并输出购买了HEXAGON的所有订单的用户名(而不是ID)

我使用的代码如下所示:

const getUserNamesFromOrders = (productName) => {
    const products = require('./resources/products.json')
  for (product of products) {
    if (product.productName === productName) {
      const productId = product.productId   
      const orders = require('./resources/orders.json')
      const users = require('./resources/users.json')
      for (order of orders) {
        const userId = order.userId 
        if (order.productId === productId) {
            for (user of users) {
                if(user.userId === order.userId) {
                   const userName = user.name
                   allUsers.push(userName)
                }
            }
        }

      }
    } 
  }
    return allUsers
} 

getUserNamesFromOrders('hexagon');
以上代码当前输出并显示数组

['john','john']

它应该在什么时候显示

['john','jane']

任何帮助都将不胜感激


谢谢

您可以尝试以下操作,而不是for of循环:

allUsers = [...new Set(orders
  .filter(o => o.productId === productName)
  .map(o => users.find(u => u.userId === o.userId).name))];

首先,我过滤掉所有不包含所需项目的订单,然后获得所有相关用户名,最后,我过滤掉重复的订单,方法是转换到一个集合并将其展开。

您的代码应该按原样工作。但是,您可以使用和方法使其更具可读性,而不是嵌套的
for
循环

首先,您必须找到给定的
productName
productId
。然后按
productId
过滤订单。然后,对于每个订单,根据
userId
users
数组中查找
name

const getUserNamesFromOrders = (productName) => {
  const products = require('./resources/products.json')
  const orders = require('./resources/orders.json');
  const users = require('./resources/users.json');

  let usernames = new Set(); // Using Set to avoid storing duplicate usernames.

  let productId = products.find(product => product.productName === productName).productId;

  let filteredOrders = orders.filter(order => order.productId === productId);

  filteredOrders.forEach(order => {
    let user = users.find(user => user.userId === order.userId);
    usernames.add(user.name);
  });

  return Array.from(usernames);
} 

let usernames = getUserNamesFromOrders('hexagon');
console.log(usernames);
现场示例:

let orders=[{“orderId”:1,“userId”:1,“productId”:001},{“orderId”:2,“userId”:2,“productId”:001},{“orderId”:3,“userId”:2,“productId”:002},{“orderId”:4,“userId”:2,“productId”:002},{“orderId”:5,“userId”:3,“productId”:003},{“orderId”:6,“userId”:1,“productId”:003},{“orderId”:7,“userId”:1,“productId”:003}];
让用户=[{“userId”:1,“name”:“john”,“email”:john@gmail.com},{“userId”:2,“name”:“mike”,“email”:mike@gmail.com},{“userId”:3,“name”:“jane”,“email”:jane@gmail.com" } ];
让products=[{“productId”:001,“productName”:“square”},{“productId”:002,“productName”:“triangle”},{“productId”:003,“productName”:“hexagon”}];
const getUserNamesFromOrders=(productName)=>{
让usernames=new Set();//使用Set避免存储重复的用户名。
让productId=products.find(product=>product.productName==productName).productId;
让filteredOrders=orders.filter(order=>order.productId==productId);
filteredOrders.forEach(订单=>{
让user=users.find(user=>user.userId==order.userId);
usernames.add(user.name);
});
返回Array.from(用户名);
} 
让usernames=getUserNamesFromOrders('hexagon');

console.log(用户名);
我在这里重播您的代码,并且始终有效

我改变了两件事:

1) 将
productId
值设置为字符串值

2) 将条件
if(product.productName==productName)
更改为
if(product.productId==productName)
,因为您传递的产品名称实际上是productId

const getUserNamesFromOrders = (productName) => {
   // Returns ordered items associated with the product name
   const ordered = orders.filter(o => {
     const productId = products.filter(p => p.productName === productName)[0].productId;
     return o.productId === productId;
   });

   // Returns usernames associated with the ordered items matching the product
   const usernames = ordered.map(o => {
     return users.filter(u => u.userId === o.userId)[0].name;
   });

   // Finally returning the unique array of users removing the duplicated values
   const filtered = usernames.filter((u, i) => usernames.indexOf(u) === i);

   return filtered;
};


console.log(getUserNamesFromOrders("hexagon"));
您还可以按以下方式将流程链接起来,以缩短流程:

   const usernames = orders.filter(o => {
     const productId = products.filter(p => p.productName === productName)[0].productId;
     return o.productId === productId;
   }).map(o => {
     return users.filter(u => u.userId === o.userId)[0].name;
   });
但是,为了解释的目的,我已经拆分了这个过程,正如代码中的注释所提到的


希望能有所帮助!

对不起,伊利亚,我注意到我在products表的原始代码中有一个重要的细节和错误,我现在已经更正了。productId是一个整数值,
productName
是一个字符串,它是传递给函数的值。此外,生成的用户名应该以无任何重复的数组values@user3354949-订单是否有
productId
productName
?@Nikhil,对不起,订单有
productId
Hi@Nikhil,这几乎起作用了。我看到的唯一问题是,代码返回了一个用户名
john
,该用户名应该重复,但是只返回一次,因此Set90;正在执行它的任务,但它似乎没有遍历
jane
order@user3354949-它应该给出预期的输出。请参阅我在回答中添加的实时示例。确保您的JSON文件正确。感谢@Nikhil提供的额外信息。我可以清楚地看到您身上发生了一些有趣的事情r最新的例子是,当你将3个对象嵌入变量中时,函数工作得很好,但是当我
需要
函数中的对象时,它似乎没有循环遍历所有可用的顺序。你知道会出现什么问题吗?JSON文件似乎是正确的,它们在其他方面独立工作以产品和用户为目标的行动separately@user3354949-在JSON文件中,确保对字符串(如
name
)使用引号
,对ID(如
userId
productId
)没有引号。此外,您还可以使用来验证JSON文件并查找任何错误。