目前我有三个数组。 AppNames
这是应用程序名称。 Number of AddOns
这是每个应用程序正在使用的附加组件的数量。 (这两个数组一起使用。例如“cirr-contentful-demo”有 1 个添加)。
看下面:
var prodArrayAppName = [],
stgArrayAppName = [],
devArrayAppName = [],
prodNoAddOns = [],
stgNoAddOns = [],
devNoAddOns = [];
var appNames = ["cirr-contentful-demo", "cirr-contentful-handler-backup", "cirr-test-app"];
var numberAddOne = [1, 5, 7]
var production = [{
"id": "16",
"heroku_application": "cirr-contentful-demo",
"stage": "Production"
},
{
"id": "4",
"heroku_application": "cirr-contentful-handler-backup",
"stage": "Staging"
},
{
"id": "9",
"heroku_application": "test-backup",
"stage": "Development"
}];
我需要循环遍历生产
对象数组,将heroku_application
名称与appNames
中的名称相匹配 数组。找到后,检查阶段类型示例:生产、暂存、开发。
将应用程序名称推送到正确的数组。 E.G 生产应用程序到 prodArrayAppName
。然后获取应用程序拥有的插件数量并将其放入正确的 NoOfAddons
中。例如 prodArrayAppName。
意味着最终的游戏应该是这样的:
prodArrayAppName = [cirr-contentful-demo]
prodNoAddOns = [1]
stgArrayAppName = [cirr-contentful-handler-backu]
stgNoAddOns = [5]
devArrayAppName = [test-backup]
devNoAddOns = [7]
这是我到目前为止尝试过的代码,但到目前为止没有运气:
production.forEach(function(a) {
appNames.forEach(function(b) {
numberAddOne.forEach(function(c) {
if (a === b.heroku_application) {
if (b.stage === "Production") {
prodArrayAppName.push(b.heroku_application);
prodNoAddOns.push(c);
} else if (b.stage === "Staging") {
stgArrayAppName.push(b.heroku_application);
stgNoAddOns.push(c);
} else {
devArrayAppName.push(b.heroku_application);
devNoAddOns.push(c);
}
}
});
});
});
最佳答案
您根本不需要显式循环来完成此操作 - 利用 reduce
:
var init = {
DevelopmentAppName:[],
DevelopmentNoAddOns:[],
StagingAppName:[],
StagingNoAddOns:[],
ProductionAppName:[],
ProductionNoAddOns:[],
};
var appNames = ["cirr-contentful-demo", "cirr-contentful-handler-backup", "cirr-test-app"];
var numberAddOne = [1,5,7]
var production = [
{
"id":"16",
"heroku_application":"cirr-contentful-demo",
"stage" : "Production"
},
{
"id":"4",
"heroku_application":"cirr-contentful-handler-backup",
"stage" : "Staging"
},
{
"id":"9",
"heroku_application":"test-backup",
"stage" : "Development"
}];
var result = production.reduce(function(p,c){
var idx = appNames.indexOf(c.heroku_application);
p[c.stage + 'AppName'].push(c.heroku_application);
p[c.stage + 'NoAddOns'].push(numberAddOne[idx] || 0);
return p;
}, init);
console.log(result);
关于javascript - 循环遍历多个数组 - 插入多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38629716/