【问题标题】:concatenate Objects data in one string将对象数据连接到一个字符串中
【发布时间】:2019-12-07 10:50:33
【问题描述】:

我有一个包含 JSON 对象的表:

    items=[
      {"label":"180","quantity":10},
      {"label":"50","quantity":35},
      {"label":"80","quantity":15},
      {"label":"180","quantity":120},
   ]

label是一个字符串,数量是一个数字,每次用户点击Add按钮时,一个newItem被添加到这个表中+{"label":"80","quantity":11}

我想要的是将这些数据连接成一个字符串,如下所示:str == '180_10,50_35,80_15,180_120'

当用户点击Add str 将是:str == '180_10,50_35,80_15,180_120,80_11'(添加了新项目 80_11)

我的方法不起作用:

  addRecup = () => {
    const newItem = {
      label: this.state.values[this.state.codeValue-1].label,
      quantity: this.state.quantite
    };
    this.setState(state => ({
      items: state.items.concat([newItem]), // add new item, it works
    }));

    let str = '';
    let concat = this.state.items.map((item,key) => (
      str = str + ',' + this.state.items.label + ',' + this.state.items.quantity // concatenate json doesn't work
    ));

    console.warn('str: ' + str); // got str: undefined,undefined,undefined...
  } 

【问题讨论】:

标签: javascript json react-native concatenation


【解决方案1】:

使用map()join()

let items=[
  {"label":"180","quantity":10},
  {"label":"50","quantity":35},
  {"label":"80","quantity":15},
  {"label":"180","quantity":120},
]

let res = items.map(v => Object.values(v).join('_')).join(',')

console.log(res)

【讨论】:

  • 谢谢它运行良好,但只是一个小问题:当我控制台记录它时,我总是缺少一个项目,下次单击添加按钮时会显示这个丢失的项目。如果我在 item[] 中有 4 个对象,我会解释更多我最有 res 变量包含这 4 个连接的对象,但只有 3 个
  • @zedArt 您提到的问题与此答案无关。请查看stackoverflow.com/questions/36085726/…
  • @zedArt 解决方案可在回答 stackoverflow.com/a/40408976/8053274 中获得
【解决方案2】:

您可以使用Array#map 方法生成_ 分隔值的数组,然后使用Array#join 组合它们。

const items = [{"label":"180","quantity":10},{"label":"50","quantity":35},{"label":"80","quantity":15},{"label":"180","quantity":120}];

console.log(items.map(v => `${v.label}_${v.quantity}`).join(','))

或者使用Array#reduce方法通过连接字符串来做同样的事情。

const items = [{"label":"180","quantity":10},{"label":"50","quantity":35},{"label":"80","quantity":15},{"label":"180","quantity":120}]; 

console.log(items.reduce((str, v, i) => str + `${i? ',' : ''}${v.label}_${v.quantity}`, ''))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2016-01-17
    • 1970-01-01
    相关资源
    最近更新 更多