【问题标题】:filter array of objects by property and get storeID associated to it按属性过滤对象数组并获取与其关联的 storeID
【发布时间】:2020-09-14 02:36:57
【问题描述】:

我是 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'

所以我的最终输出应该是“3405”、“5677”、“2341”。 (以,分隔的一串storeID)

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

【问题讨论】:

  • 过滤器->地图->加入。或者只是使用带有if 条件的简单for 循环

标签: javascript arrays loops object arraylist


【解决方案1】:

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));

【讨论】:

    【解决方案2】:

    借助filtermapjoin 运算符。

    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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 2019-05-04
      • 2020-01-20
      • 1970-01-01
      相关资源
      最近更新 更多