Javascript 存储数组值时出错
error in Javascript in storing the array value
的输出
result[0].brand_id = ["59df686fe30af41be049417f","59df68eca39cf51b40c566ab"]
并且我想将这些 id 找到的值存储在单个存储中 'brand'
我的密码是
var data = {};
data['brands'] = [];
async.each(result[0].brand_id, function (brand,callback) {
Brand.findById(brand,function(err,result){
if(err){
callback("there is an error");
}
//console.log(result.brand_name);
data['brands'] = {
brand: result.brand_name,
dosage: result.dosage_id
};
console.log(data); // it is correct but but shows two single storage
});
callback();
},function (err,data) {
if(err){
console.log(err);
}
console.log(data); // it show output undefined
});
我希望输出为
{ brands:
[ { brand: 'a', dosage: ["59df686ee30af41be049417e"] },
{ brand: 'b', dosage: ["59df68eca39cf51b40c566aa"] } ] }
我卡在这里了,请解决这个问题。
您必须将 data['brand']
创建为数组,并且必须将值推入其中。
示例解决方案:
if(!data['brand']) data['brand'] = []; // to check if it is the first time you are inserting inside data['brand'], in which case it needs to be initialized.
data['brand'].push({
brand: result.brand_name,
dosage: [result.dosage_id]
});
result[0].brand_id = ["59df686fe30af41be049417f","59df68eca39cf51b40c566ab"]
并且我想将这些 id 找到的值存储在单个存储中 'brand'
我的密码是
var data = {};
data['brands'] = [];
async.each(result[0].brand_id, function (brand,callback) {
Brand.findById(brand,function(err,result){
if(err){
callback("there is an error");
}
//console.log(result.brand_name);
data['brands'] = {
brand: result.brand_name,
dosage: result.dosage_id
};
console.log(data); // it is correct but but shows two single storage
});
callback();
},function (err,data) {
if(err){
console.log(err);
}
console.log(data); // it show output undefined
});
我希望输出为
{ brands:
[ { brand: 'a', dosage: ["59df686ee30af41be049417e"] },
{ brand: 'b', dosage: ["59df68eca39cf51b40c566aa"] } ] }
我卡在这里了,请解决这个问题。
您必须将 data['brand']
创建为数组,并且必须将值推入其中。
示例解决方案:
if(!data['brand']) data['brand'] = []; // to check if it is the first time you are inserting inside data['brand'], in which case it needs to be initialized.
data['brand'].push({
brand: result.brand_name,
dosage: [result.dosage_id]
});