1

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

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

thank you it works good but just a little issue : when I console.log it I have always an item missing, this missed item is shown next time when I click Add button. I explain more if I have 4 object in item[] I most have res variable contains this 4 object concatenated but there is only 3
@zedArt the issue you are mentioning is something not related to this answer. please check stackoverflow.com/questions/36085726/…
@zedArt solution available in answer stackoverflow.com/a/40408976/8053274
1

You can use Array#map method to generate array of _ separated values and then use Array#join to combine them.

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(','))

Or use Array#reduce method to do the same thing by concatenating string.

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}`, ''))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.