Search code examples
javascriptjsonreact-nativeconcatenation

concatenate Objects data in one string


I have a table that contains objects in JSON:

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

label is a string and quantity is a number, and every time user click on Add button a newItem is added to this table + {"label":"80","quantity":11}

what I want is to concatenate this data into one string like this: str == '180_10,50_35,80_15,180_120'

and when user click on Add str will be : str == '180_10,50_35,80_15,180_120,80_11' (with new item added 80_11)

my approach doesn't work :

  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...
  } 

Solution

  • Using map() and 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)