我对学习编码还很陌生。所以我可能会弄错很多基础知识。
基本上,我通过请求 promise 从两个不同的帐户下载 API 内容,并希望将它们合并到更大的数组中。我正在努力从请求 promise 函数中转义本地数据并将其与第二个数组组合
这是我到目前为止得到的:
//request the site and do some stuff with the data
rp(rpOptions)
.then(function (parsedBody) {
let incomingData1 = (parsedBody); //turning data into a value to change it a little
incomingData1.forEach((incomingData1) => {incomingData1.yearsRetired = 0}); //to add a new property
incomingData1 = JSON.stringify(parsedBody, ["favFood", "age", "work", "yearsRetired"], 2); //to filter only relevant properties into a JSON thing (i eventually want to save it to a txt file)
});
然后我会对第二个帐户执行相同的操作,然后尝试在函数之外获取该数据并将其合并到单个数组中,使其看起来像这样:
{
"first_account_name": {
"individual1": {
"favFood": 'fries',
"age": 23,
"work": 'astronaut'
"yearsRetired": 0
},
"individual2": {
"favFood": 'banana',
"age": 55,
"work": 'zookeeper'
"yearsRetired": 0
{
...
}
},
"second_account_name": { ... }
"individual6": {
"favFood": 'apple',
"age": 49,
"work": 'dinosaur'
"yearsRetired": 0
"individual7": {
"favFood": 'sausage',
"age": 33,
"work": 'doctor'
"yearsRetired": 0
{
...
}
如何将数据放入 rp 之外的变量中?我该如何设置它,使其最终像一个嵌套数组?
非常感谢,很抱歉让您感到困惑:P
您正在寻找的是一个全局数组,它可以在每个正确调用的 Promise 请求上将数据推送到其中。因此,首先,创建一个简单的数组并将其放置在页面顶部,或者如果您使用类,只需将其插入到相应的字段中。
Let accountDetails = [];
接下来,在then函数内部像这样调用这个变量,
rp(rpOptions)
.then(function (parsedBody) {
let incomingData1 = (parsedBody);
incomingData1.forEach((incomingData1) => {incomingData1.yearsRetired = 0});
incomingData1 = JSON.stringify(parsedBody, ["favFood", "age", "work", "yearsRetired"], 2);
accountDetails.push({
"individual1" : incomingData1
})
});
我是一名优秀的程序员,十分优秀!