[英]Convert string separated by comma in json object to array
I want to convert this json object that contain string value separated by comma to array:我想将包含以逗号分隔的字符串值的 json object 转换为数组:
[
{id: 1,
name: 'book',
colors: 'red, yellow, blue'
},
id: 2,
name: 'book',
colors: 'red, yellow, blue'
}
]
to:到:
[
{id: 1,
name: 'book',
colors: ['red', 'yellow', 'blue']
},
id: 2,
name: 'book',
colors: ['red', 'yellow', 'blue']
}
]
in javascript, thank you! javascript,谢谢!
You can do the following,您可以执行以下操作,
data = [ {'id': 1, 'name': 'book', 'colors': 'red, yellow, blue' }, {'id': 2, 'name': 'book', 'colors': 'red, yellow, blue' } ]; ret = data.map((item) => { return {...item, colors: item.colors.split(',').map(item => item.trim())}; }) console.log(ret);
Strings get into arrays in each object.字符串在每个 object 中进入 arrays。
let arr = [ {id: 1, name: 'book', colors: 'red, yellow, blue' }, {id: 2, name: 'book', colors: 'red, yellow, blue' } ] for (let index in arr) { let colorsIntoArr = arr[index].colors.split(','); arr[index].colors = colorsIntoArr; } /* [ { "id": 1, "name": "book", "colors": [ "red", " yellow", " blue" ] }, { "id": 2, "name": "book", "colors": [ "red", " yellow", " blue" ] } ] */ console.log(arr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.