from my api I get the following array:
const apiResponse = [
{
"accountBillNumber": "123456789",
"amountMoney": "0.00"
},
{
"accountBillNumber": "987654321",
"amountMoney": "0.01"
},
];
I would like to write a very short code that will always change the value from accountBillNumber to value.replace(/(^\d{2}|\d{4})+?/g, '1ドル '). Can it be done in a modern way with one line using es6 +?
asked May 26, 2020 at 8:44
reactdto2
1231 gold badge2 silver badges9 bronze badges
3 Answers 3
Use the .forEach() method.
const apiResponse = [
{
"accountBillNumber": "123456789",
"amountMoney": "0.00"
},
{
"accountBillNumber": "987654321",
"amountMoney": "0.01"
},
];
apiResponse.forEach(x => x.accountBillNumber = x.accountBillNumber.replace(/(^\d{2}|\d{4})+?/g, '1ドル '));
console.log(apiResponse);
Or the .map() method to create a new array, as @Mamun's answer suggests.
const apiResponse = [
{
"accountBillNumber": "123456789",
"amountMoney": "0.00"
},
{
"accountBillNumber": "987654321",
"amountMoney": "0.01"
},
];
const result = apiResponse.map(x => {
const { accountBillNumber, ...rest } = x;
return {
accountBillNumber: accountBillNumber.replace(/(^\d{2}|\d{4})+?/g, '1ドル '),
...rest
};
});
console.log(result);
answered May 26, 2020 at 8:47
Daan
2,8101 gold badge23 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
reactdto2
You removed "amountMoney". I would like to save object, but only value in accountBillNumber I want to formatted using regex.
Ilijanovic
you could also destrucuture the object
apiResponse.forEach(({ accountBillNumber: bill }) => bill = bill.replace(/(^\d{2}|\d{4})+?/g, '1ドル '));You can try the following way using Array.prototype.map():
const apiResponse = [
{
"accountBillNumber": "123456789",
"amountMoney": "0.00"
},
{
"accountBillNumber": "987654321",
"amountMoney": "0.01"
},
];
var res = apiResponse.map(v => {
return {
amountMoney: v.amountMoney,
accountBillNumber: v.accountBillNumber.replace(/(^\d{2}|\d{4})+?/g, '1ドル ')
};
});
console.log(res)
answered May 26, 2020 at 8:54
Mamun
69k9 gold badges51 silver badges62 bronze badges
1 Comment
Daan
I think it would be helpful to use rest parameters here. I included it in my answer. Because the APIs response could always change. And you wouldn't want to hard code all the objects properties.
apiResponse.map(x=>({...x,accountBillNumber:x.accountBillNumber.replace(/(^\d{2}|\d{4})+?/g, '1ドル')}))
Try this
answered May 26, 2020 at 9:10
Aditya V
5782 gold badges8 silver badges18 bronze badges
Comments
lang-js
accoutnBillNumberor its value?