Reputation: 485
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...
}
Upvotes: 1
Views: 2164
Reputation: 115212
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}`, ''))
Upvotes: 1
Reputation: 20039
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)
Upvotes: 2