gpt4 book ai didi

node.js - 更新 JSON 数组特定字符串

转载 作者:太空宇宙 更新时间:2023-11-03 23:54:16 25 4
gpt4 key购买 nike

我遇到的问题是我正在从 stripe 退回一组用户信用卡。由于 Stripe 将默认卡或“源”与卡对象分开,因此我需要将响应附加回我的应用程序。我的应用程序有一个带有 isDefault BOOL 变量的结构。应用程序部分实际上无法更改。

在我下面发布的 JSON 代码中,我使用 aarows 做了一些评论,说明我想要新的 key: value 的位置。简而言之,如果其自己的 {} 中的任何卡与用户拥有的默认卡匹配,那么我想将键值:"isDefault": true 仅插入到与默认卡匹配的 {} 中。

我已经玩弄这个有一段时间了,但我被困住了。我已使用 for 循环在数组中搜索匹配的卡 ID,但无法弄清楚如何附加到卡的特定 {} 中,它只是进入整个数组。

带注释的 JSON 响应:

{
"cardsData": [
{
"id": "card_328746328746",
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Discover",
"country": "US",
"customer": "cus_djklfhdskljfhs",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 9,
"exp_year": 2023,
"fingerprint": "dfhsdkljfsdlkf",
"funding": "credit",
"last4": "1117",
"metadata": {},
"name": null,
"tokenization_method": null
},
{
"id": "card_kjdslhfjdhf", <-- HAPPENS TO BE DEFAULT CARD, NEED TO INSERT HERE
"object": "card",
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": null,
"address_zip_check": null,
"brand": "Visa",
"country": "US",
"customer": "cus_dkljfhdkjfhd",
"cvc_check": "pass",
"dynamic_last4": null,
"exp_month": 4,
"exp_year": 2054,
"fingerprint": "dfjsklkjfhsd",
"funding": "credit",
"last4": "4242",
"metadata": {},
"name": null,
"tokenization_method": null
"isDefault": true <-- THIS CURRENTLY DOES NOT EXIST, THIS IS WHERE I NEED HELP TO GET THIS INSERTED
}
]
}

Node JS/云函数代码:

exports.getCardsTest = functions.https.onRequest((req, res) => {
if (req.method !== 'POST') {
return;
}
const customerId = req.body.stripeId;
stripe.customers.retrieve(
customerId,
{

},
function (err, customer) {
const cardsData = customer.sources.data;
const defaultCard = customer.default_source;

var isDefault = false; //check of vairable value
console.log('isDefault before:', isDefault);

for (var i = 0; i < cardsData.lenth; i++); {
if (cardsData[i].id == defaultCard);
isDefault = true;
cardsData.push({ isDefault }); <--THIS IS WHERE I NEED HELP, I NEED isDefault: true APPENDED TO THE ARRAY STRING {} MATCHING THE KEY VALUE OF THE DEFAULT CARD
};

console.log('isDefaultAfter:', isDefault); // check to make sure IF statement is working

return res.status(200).send({ cardsData });
}
);

});

最佳答案

您可以像这样更新数组中的值

for (var i = 0; i < cardsData.length; i++); {
if (cardsData[i].id === defaultCard) {
cardsData[i].isDefault = true
}
}

你的if没用,因为缺少一部分,而且你还在插入卡片数组,我认为

关于node.js - 更新 JSON 数组特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58063163/

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