I want to extract the name and rate from each element of the array below, and turn them into an array of object
[
'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
]
The following is what i expect to get:
[
{"name":BTCUSDT, "rate":0.01%},
{"name":ETHUSDT,"rate":0.01%},
{"name":BCHUSDT,"rate":0.01%},
]
Appreciate for any suggestions.
CodePudding user response:
Try using arr.reduce()
const arr = [
'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
];
const res = arr.reduce((acc, item) => {
debugger;
const splitArr = item.split(' ');
acc.push({
[splitArr[0]]: splitArr[1].split('\t')[4]
});
return acc;
}, [])
console.log(res)
CodePudding user response:
You can use a combination of array mapping and string splitting to achieve this:
const arr = [
'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
];
const result = arr.map(item => {
const elements = item.split('\t');
const name = elements[0].split(" ")[0];
return {
name,
rate: elements[4]
};
});
console.log(result);
CodePudding user response:
const arr = [
'BTCUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3000% / -0.3000%\t0.3000% / -0.3000%',
'ETHUSDT Perpetual\t8h\t05:14:44\t0.0100%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%',
'BCHUSDT Perpetual\t8h\t05:14:44\t-0.0135%\t0.01%\t0.3750% / -0.3750%\t0.3750% / -0.3750%'
];
var data = [];
const result = arr.reduce((data, value) => {
const splitArray = value.split(' ');
var params = {
name: splitArray[0],
rate: splitArray[1].split('\t')[4]
}
data.push(params);
return data;
}, [])
const output = result;
console.log(output);