How to convert this Object into an Array?

Leon Gaban
{
  "ethereum": {
    "balance":"2",
    "value":1382.4,
    "id":"ethereum",
    "name":"Ethereum",
    "symbol":"ETH",
    "rank":"2",
    "price_usd":"691.204",
    "24h_volume_usd":"2420600000.0",
    "percent_change_1h":"0.02",
    "percent_change_24h":"0.51",
    "percent_change_7d":"0.98",
    "percentage":14.34
  },
  "bitcoin": {
    "balance":"1",
    "value":8255.95,
    "id":"bitcoin",
    "name":"Bitcoin",
    "symbol":"BTC",
    "rank":"1",
    "price_usd":"8255.96",
    "24h_volume_usd":"6128880000.0",
    "percent_change_1h":"0.02",
    "percent_change_24h":"0.43",
    "percent_change_7d":"-3.49",
    "percentage":85.66
  }
} 

The above object was converted from this Array below then saved into localStorage.

What I'm trying to do is re-create the following Array:

[
  {
    24h_volume_usd: "6124340000.0",
    balance: "1",
    id: "bitcoin",
    name: "Bitcoin",
    percent_change_1h: "-0.1",
    percent_change_7d: "-3.46",
    percent_change_24h: "0.47",
    percentage: 85.66,
    price_usd: "8256.98",
    rank: "1",
    symbol: "BTC",
    value: 8256.98
  },
  {
    4h_volume_usd: "2420170000.0",
    balance: "2",
    id: "ethereum",
    name: "Ethereum",
    percent_change_1h: "-0.07",
    percent_change_7d: "0.95",
    percent_change_24h: "0.49",
    percentage: 14.34,
    price_usd: "691.074",
    rank: "2",
    symbol: "ETH",
    value: 1382.14
  }
]

The Array to Object logic

export const calculatePercentage = (portfolio, coin) => {
  portfolio.push(coin);

  const addValue = c => c.value;
  const values = R.chain(addValue, portfolio);
  const total = values.reduce((acc, val) => acc + val);

  const updatedPortfolio = portfolio.map((c) => {
    c.percentage = round((c.value / total) * 100);
    return c;
  });

  const moonPortfolio = arrayToObject(updatedPortfolio);

  // Local Storage saved here:
  window.localStorage.setItem('moonPortfolio', JSON.stringify(moonPortfolio));

  return updatedPortfolio;
};
yadejo

You can use the Object.values method to get all values in the object in an array:

const object = {
  "ethereum": {
    "balance":"2",
    "value":1382.4,
    "id":"ethereum",
    "name":"Ethereum",
    "symbol":"ETH",
    "rank":"2",
    "price_usd":"691.204",
    "24h_volume_usd":"2420600000.0",
    "percent_change_1h":"0.02",
    "percent_change_24h":"0.51",
    "percent_change_7d":"0.98",
    "percentage":14.34
  },
  "bitcoin": {
    "balance":"1",
    "value":8255.95,
    "id":"bitcoin",
    "name":"Bitcoin",
    "symbol":"BTC",
    "rank":"1",
    "price_usd":"8255.96",
    "24h_volume_usd":"6128880000.0",
    "percent_change_1h":"0.02",
    "percent_change_24h":"0.43",
    "percent_change_7d":"-3.49",
    "percentage":85.66
  }
} 

const array = Object.values(object)
console.log(array)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related