skip to Main Content

I want to extract the name and rate from each element of the array below, and turn them into an array of object

[
  'BTCUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3000% / -0.3000%t0.3000% / -0.3000%',
  'ETHUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3750% / -0.3750%t0.3750% / -0.3750%',
  'BCHUSDT Perpetualt8ht05:14:44t-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.

3

Answers


  1. Try using arr.reduce()

    const arr = [
      'BTCUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3000% / -0.3000%t0.3000% / -0.3000%',
      'ETHUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3750% / -0.3750%t0.3750% / -0.3750%',
      'BCHUSDT Perpetualt8ht05:14:44t-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)
    Login or Signup to reply.
  2. You can use a combination of array mapping and string splitting to achieve this:

    const arr = [
      'BTCUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3000% / -0.3000%t0.3000% / -0.3000%',
      'ETHUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3750% / -0.3750%t0.3750% / -0.3750%',
      'BCHUSDT Perpetualt8ht05:14:44t-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);
    
    Login or Signup to reply.
  3. const arr = [
      'BTCUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3000% / -0.3000%t0.3000% / -0.3000%',
      'ETHUSDT Perpetualt8ht05:14:44t0.0100%t0.01%t0.3750% / -0.3750%t0.3750% / -0.3750%',
      'BCHUSDT Perpetualt8ht05:14:44t-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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search