gpt4 book ai didi

javascript - 如何将这个对象转换为数组?

转载 作者:行者123 更新时间:2023-12-02 12:41:15 24 4
gpt4 key购买 nike

{
"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
}
}

上面的对象是从下面这个数组转换而来的,然后保存到 localStorage 中。

我想做的是重新创建以下数组:

[
{
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
}
]

数组到对象逻辑

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;
};

最佳答案

您可以使用Object.values方法获取数组中对象的所有值:

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)

关于javascript - 如何将这个对象转换为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50418799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com