John Donvan
John Donvan

Reputation: 35

Re-format JSON in Javascript

Trying to reformat the response from an API query, but running into issues. Attempted map but didn't work.

main.data.daily(symbol, 'main', 'json').then(data=> ....);

Current response format:

'data':{
  '2018-03-13':
    { '1. open': '32.8500',
      '2. high': '33.3600',
      '3. low': '32.8500',
      '4. close': '33.1400',
      '5. volume': '834894' 
    },
    ...
 }

This is the desired Format:

[{ 
 date: '2018-03-13'
 open: 32.85, 
 high: 33.36, 
 low: 33.85,
 close: 33.14, 
 volume: 855448
},
...
]

Tried the following but no cigar:

data.map(val, i, data => {
            return {
                date: i,
                open: val['1. open'],
                high: val['2. high'],
                low: val['3. low'],
                close: val['4. close'],
                volume: val['5. volume']
            }
        });

var data = {
  '2018-03-13': {
    '1. open': '32.8500',
    '2. high': '33.3600',
    '3. low': '32.8500',
    '4. close': '33.1400',
    '5. volume': '834894'
  },
}

data = data.map(val, i, data => {
  return {
    date: i,
    open: val['1. open'],
    high: val['2. high'],
    low: val['3. low'],
    close: val['4. close'],
    volume: val['5. volume']
  }
});
console.log(data)

Upvotes: 1

Views: 83

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386520

You could reformat your objects by using Object.entries and Object.assign. For getting a new key without leading number and dot, you could take a regular expression which separates the wanted part for a new key.

var data = { '2018-03-13': { '1. open': '32.8500', '2. high': '33.3600', '3. low': '32.8500', '4. close': '33.1400', '5. volume': '834894' }, '2018-03-12': { '1. open': '32.3900', '2. high': '32.8050', '3. low': '32.2800', '4. close': '32.6800', '5. volume': '855448' } },
    result = Object
        .entries(data)
        .map(([date, object]) => Object.assign(
            { date },
            ...Object.entries(object).map(([k, v]) => ({ [k.match(/\w+$/)]: +v })))
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 5

Related Questions