【问题标题】:Concatenate strings within array of objects连接对象数组中的字符串
【发布时间】:2021-08-03 22:41:49
【问题描述】:

我有如下的对象数组。我想遍历它并获取Closed 属性值。它应该是每个对象中找到的所有值的串联。

例如在下面的情况下,我希望最终结果为121212,因为它在所有 3 个对象中有 12 个。

const data = [
    {
      "personId": "1208007855",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "1559363884",
      "details": {
        "Closed": "12"
      }
    },
    {
      "personId": "973567318",
      "details": {
        "Closed": "12"
      }
    }
  ]

谁能告诉我如何实现这一点。我尝试了这种方式,但无法成功实现结果。我只能得到第一个对象的值。不知道如何在这个循环中连接和存储下一个值

可能存在某些对象可能没有Closed 属性的情况。

const totalClosed = data.forEach(function (arrayItem) {
    const x = arrayItem.details.Closed;
    console.log(x);
});

【问题讨论】:

    标签: javascript arrays reactjs loops object


    【解决方案1】:

    尝试以下方法:

    const data = [
        {
          "personId": "1208007855",
          "details": {
            "Closed": "12"
          }
        },
        {
          "personId": "1559363884",
          "details": {
            "Closed": "12"
          }
        },
        {
          "personId": "973567318",
          "details": {
            "Closed": "12"
          }
        }
      ];
      result = '';
      for (let i in data) {
          result += data[i].details.Closed
      }
    

    【讨论】:

    • data[i].details.Closedundefined的情况如何
    • 在这种情况下使用result = ''; for (let i in data2) { if (typeof data2[i]?.details?.Closed != 'undefined') result += data2[i]?.details?.Closed }
    【解决方案2】:

    你可以使用.reduce函数:

    data.reduce((accumulator, item) => accumulator += item.details.Closed, '')

    => 121212

    【讨论】:

    • data[i].details.Closed undefined的情况如何
    • 如果字段未定义,可以写item.details?.Closed ?? ''而不是item.details.Closed。如果item.details.Closed 是空值,它将返回一个空字符串:data.reduce((accumulator, item) => accumulator += item.details?.Closed ?? '', '')
    【解决方案3】:
    let str = "";
    for(let i=0; i<data.length;i++){
    str+= data[i].details.Closed;
    }
    
    console.log(str);
    

    此外,对于 forEach,元素可能不会以相同的顺序(0 到 n)进行处理,您可能会发现与预期不同的结果。

    【讨论】:

      【解决方案4】:

      如果你想要一个字符串并且有一个数组,最好的方法是reduce:

      const totalClosed = data.reduce(function (accumulator, currentVal) {
          const closed = currentVal.details.Closed || '';
          return accumulator + closed;
      }, '');
      

      【讨论】:

        【解决方案5】:
        let str = ''
        const totalClosed = data.forEach(function (arrayItem) {
          if(arrayItem.details.Closed){
                str += arrayItem.details.Closed;
          }
        });
        
        console.log(str)
        

        如果已关闭字段存在,您可以创建一个空字符串并添加到其中,如果“已关闭”中有另一个条件,您可以在 if 语句中检查那里。

        【讨论】:

          【解决方案6】:

          使用 foreach 与您尝试的方式完全相同:

          const data = [
            {
              personId: '1208007855',
              details: {
                Closed: '12'
              }
            },
            {
              personId: '1559363884',
              details: {
                Closed: '12'
              }
            },
            {
              personId: '973567318',
              details: {
                Closed: '12'
              }
            }
          ];
          
          let totalClosed = '';
          
          data.forEach(function (arrayItem) {
            totalClosed = totalClosed + arrayItem.details.Closed;
          });
          
          console.log(totalClosed);
          

          【讨论】:

            【解决方案7】:

            您可以通过解构化简器中的条目并将Closed 值连接到正在运行的res(结果)来减少数据条目。您可以使用 nullish-coalescing 运算符 (??) 在连接时使用空字符串而不是 undefined

            const data = [
              { "personId": "1208007855" , "details": { "Closed": "12" } },
              { "personId": "1559363884" , "details": { "Closed": "12" } },
              { "personId": "0000000000" , "details": { "Open"  : "8"  } }, // New!
              { "personId": "973567318"  , "details": { "Closed": "12" } }
            ];
            
            const value = data.reduce((res, { details: { Closed } }) => res + (Closed ?? ''), '');
            
            console.log(value);

            【讨论】:

              【解决方案8】:

              如果你想使用循环来实现,请尝试使用:

              const data = [
                  {
                    "personId": "1208007855",
                    "details": {
                      "Closed": "12"
                    }
                  },
                  {
                    "personId": "1559363884",
                    "details": {
                      "Closed": "12"
                    }
                  },
                  {
                    "personId": "973567318",
                    "details": {
                      "Closed": "12"
                    }
                  }
                ];
              var res= ''
              data.forEach((item)=>{if(item.details.Closed){ res += item.details.Closed;}})
              console.log(res)
              

              这也可以通过使用高阶函数来完成: 尝试使用:

              data.reduce((res, item) =>{if(item.details.Closed)
               res += item.details.Closed;
              return res}, '')
              

              【讨论】:

                【解决方案9】:

                在功能方面,使用reduce

                const data = [
                    {
                        "personId": "1208007855",
                        "details": {
                            "Closed": "12",
                            "Analyze": "10"
                        }
                    },
                    {
                        "personId": "1559363884",
                        "details": {
                            "Closed": "12",
                            "Analyze": "10"
                        }
                    },
                    {
                        "personId": "973567318",
                        "details": {
                            "Closed": "12",
                            "Analyze": "10"
                        }
                    }
                ]
                
                const { Closed, Analyze } = data.reduce((acc, cur) => {
                    acc.Closed += cur?.details?.Closed ?? ''
                    acc.Analyze += cur?.details?.Analyze ?? ''
                   return acc
                }, { Closed: "", Analyze: "" })
                console.log({ Closed, Analyze })

                【讨论】:

                • @Naren- 如果我有另一个属性“Analyze”和“Closed”,我如何在单个 reduce 中连接这两个值?
                • 您可以使用对象保存所有字符串作为结果。让我这样做
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-06-29
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-04-09
                相关资源
                最近更新 更多