I am trying to perform .toLocaleString()
on each of the arrays elements.
I am performing this for example to change 1111' to
1,111`.
The data I am trying to access:
"Data": {
"id": 1182,
"time": 1637193600,
"symbol": "BTC",
"partner_symbol": "BTC",
"zero_balance_addresses_all_time": 882855842,
"unique_addresses_all_time": 920909797,
"new_addresses": 476543,
"active_addresses": 992178,
"average_transaction_value": 18.723511893530098,
"block_height": 710345,
"hashrate": 163489266.17996278,
"difficulty": 22674148233453.105,
"block_time": 595.6643356643356,
"block_size": 1267871,
"current_supply": 18877162,
"transaction_count": 293867,
"transaction_count_all_time": 688002252,
"large_transaction_count": 29400
}
My code in attempt to manipulate the array:
getCryptoBlockchainData(selectedCrypto).then(cryptoTradingSignal => {
if (cryptoTradingSignal.hasOwnProperty('id')) {
cryptoTradingSignal.forEach(function (item, i) {
this[i] = item.toLocaleString();
}, cryptoTradingSignal);
return this.setState({cryptoBlockchainData: cryptoTradingSignal});
} else {
return this.setState({cryptoBlockchainData: undefined});
}
});
}
CodePudding user response:
You can't forEach over the properties of an object. You can convert it to an array, do your thing, then convert it back to an object.
getCryptoBlockchainData(selectedCrypto).then(cryptoTradingSignal => {
if (cryptoTradingSignal.hasOwnProperty('id')) {
const newSignal = Object.fromEntries(
Object.entries(cryptoTradingSignal).map(([k, v]) => ([k, v.toLocaleString()]))
);
return this.setState({cryptoBlockchainData: newSignal});
} else {
return this.setState({cryptoBlockchainData: undefined});
}
});
CodePudding user response:
you could probably use Array.prototype.map()
for that.
For your code maybe something like
const newArray = Object.keys(object["Data"]).map(item => object[item].toLocaleString()));
See the docs here.
CodePudding user response:
You can iterate through the object keys using the Object.keys() function and change the values you want.
const dataObj = {
"id": 1182,
"time": 1637193600,
"symbol": "BTC",
"partner_symbol": "BTC",
"zero_balance_addresses_all_time": 882855842,
"unique_addresses_all_time": 920909797,
"new_addresses": 476543,
"active_addresses": 992178,
"average_transaction_value": 18.723511893530098,
"block_height": 710345,
"hashrate": 163489266.17996278,
"difficulty": 22674148233453.105,
"block_time": 595.6643356643356,
"block_size": 1267871,
"current_supply": 18877162,
"transaction_count": 293867,
"transaction_count_all_time": 688002252,
"large_transaction_count": 29400
}
Object.keys(dataObj).forEach(key => dataObj[key] = dataObj[key].toLocaleString());
console.log(dataObj);
EDIT:
Incase your Object is nested as in your example, you also need to use the 'Data' key:
Object.keys(dataObj['Data']).forEach(key => dataObj['Data'][key] = dataObj['Data'][key].toLocaleString());