Reputation: 1738
i have two array. And i want update second array with first array data if found same data. Here is my first array :
var namaFile = [
{
billingID: "90009388",
customerID: "C20121121221327_249",
name: "201409011141106_082895250262"
},
{
billingID: "90009400",
customerID: "7885000000007804",
name: "201410201141125_08287045931"
},
{
billingID: "90009388",
customerID: "C20121121221327_249",
name: "201410011171208_082895250262"
}
];
Here second array :
var emailAddr = [
{
customerID: "C20121121221327_249",
email: "[email protected]"
},
{
customerID: "7885000000007804",
email: "[email protected]"
}
];
Here is my code, but won't work.
for (var i = 0; i < namaFile.length; i++) {
var files = [];
for (var j = 0; j < emailAddr.length; j++) {
if (namaFile[i].customerID == emailAddr[j].customerID) {
files.push(namaFile[i].name);
emailAddr[j]['files'] = files;
}
}
}
console.log(emailAddr);
My expected result is like this :
var emailAddr = [
{
customerID: "C20121121221327_249",
email: "[email protected]",
files : [
"201409011141106_082895250262","201410011171208_082895250262"
]
},
{
customerID: "7885000000007804",
email: "[email protected]",
files : [
"201410201141125_08287045931"
]
}
];
How to create that result? Thank you.
Upvotes: 0
Views: 44
Reputation: 3669
Swap for(...) {
. Example
for (var j = 0; j < emailAddr.length; j++) {
var files = [];
for (var i = 0; i < namaFile.length; i++) {
if (namaFile[i].customerID == emailAddr[j].customerID) {
files.push(namaFile[i].name);
emailAddr[j]['files'] = files;
}
}
}
Upvotes: 1
Reputation: 7640
emailAddr[j]['files'] = files;
by this line you are overwriting emailAddr[j]['files']
each times
var namaFile = [{
billingID: "90009388",
customerID: "C20121121221327_249",
name: "201409011141106_082895250262"
}, {
billingID: "90009400",
customerID: "7885000000007804",
name: "201410201141125_08287045931"
}, {
billingID: "90009388",
customerID: "C20121121221327_249",
name: "201410011171208_082895250262"
}];
var emailAddr = [{
customerID: "C20121121221327_249",
email: "[email protected]"
}, {
customerID: "7885000000007804",
email: "[email protected]"
}];
for (var i = 0; i < namaFile.length; i++) {
var files = [];
for (var j = 0; j < emailAddr.length; j++) {
if (emailAddr[j]['files'] == null)
emailAddr[j]['files'] = [];
if (namaFile[i].customerID == emailAddr[j].customerID) {
emailAddr[j]['files'].push(namaFile[i].name);
}
}
}
console.log(emailAddr);
Upvotes: 1
Reputation: 1
Hi You can use underscore js which can be a good option for you if you have lot of object/data manipulation in your code.
and then your code may look like:
_.each(emailAddr, function(customer) {
var files = _.where(namaFile, {customerID: customer.customerID});
customer.files = _.map(files, function(file) {
return file.name;
});
});
Upvotes: 0