繁体   English   中英

按属性过滤对象数组并获取与其关联的 storeID

[英]filter array of objects by property and get storeID associated to it

我是stackoverflow的新手。 如果我不能正确地表达我的问题,请原谅。

当搜索条件匹配时,我对数组过滤和从中获取属性详细信息有特定要求。 这是我的要求。

let userEntered = "Zone 1"

let givenArray = 
[0]: { zone: 'Zone 1', storeId: '3405'}
[1]: { zone: 'Zone 2', storeId: '3455'}
[2]: { zone: 'Zone 2', storeId: '4125'}
[3]: { zone: 'Zone 1', storeId: '5677'}
[4]: { zone: 'Zone 2', storeId: '1123'}
[5]: { zone: 'Zone 3', storeId: '9845'}
[6]: { zone: 'Zone 1', storeId: '2341'}

当用户进入Zone 1时,我们必须搜索givenArray并过滤掉那些zone='Zone 1'

完成后,我需要将 storeId 关联到它。 因此,根据上述情况,与Zone 1关联的 storeId 为 '3405'、'5677'、'2341'

所以我最终的 output 应该是“3405”、“5677”、“2341”。 (作为由,分隔的 storeID 字符串)

有人可以让我知道如何实现这一目标。 我可以使用常规过滤方法来获取具有zone=="Zone1"的 arrays 。 但我无法从中获取storeIds并将其作为字符串保存在我的 output 中。 有人可以帮助/建议一种方法来做到这一点。

借助过滤器map加入运营商。

 const userEntered = "Zone 1"; const givenArray = [ { zone: 'Zone 1', storeId: '3405'}, { zone: 'Zone 2', storeId: '3455'}, { zone: 'Zone 2', storeId: '4125'}, { zone: 'Zone 1', storeId: '5677'}, { zone: 'Zone 2', storeId: '1123'}, { zone: 'Zone 3', storeId: '9845'}, { zone: 'Zone 1', storeId: '2341'}, ]; const result = givenArray.filter(item => item.zone === userEntered).map(item => item.storeId).join(', '); console.log(result);

 var arr = [{ zone: 'Zone 1', storeId: '3405'},{ zone: 'Zone 2', storeId: '3455'},{ zone: 'Zone 2', storeId: '4125'},{ zone: 'Zone 1', storeId: '5677'},{ zone: 'Zone 2', storeId: '1123'},{ zone: 'Zone 3', storeId: '9845'},{ zone: 'Zone 1', storeId: '2341'}] var result = arr.filter(item => item.zone === "Zone 1").forEach(x=>console.log(x.storeId));

暂无
暂无

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

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