Giả sử, chúng ta có một chuỗi như sau:
const str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true';
Chúng ta cần viết một hàm JavaScript nhận vào một chuỗi như vậy. Hàm nên tách chuỗi theo '|' để tách option và value của nó và chuyển đổi thành mảng các object như sau:
const output = [
{ "option": "Option 1", "value": false },
{ "option": "Option 2", "value": false },
{ "option": "Option 3", "value": false },
{ "option": "Option 4", "value": true }
];Ví dụ
const str = 'Option 1|false|Option 2|false|Option 3|false|Option 4|true';
const stringToObject = (str = '') => {
const res = [];
for (let i = 0, a = str.split('|'); i < a.length; i += 2) {
const option = a[i], value = JSON.parse(a[i + 1]);
res.push({ option, value });
}
return res;
};
console.log(stringToObject(str));Kết quả
Kết quả hiển thị trong console sẽ là:
[
{ option: 'Option 1', value: false },
{ option: 'Option 2', value: false },
{ option: 'Option 3', value: false },
{ option: 'Option 4', value: true }
]