i am newly learner nodejs developer
i have two txt files like file1.txt and file2.txt file1.text data is different and file2.txt data is different but customerid is same beased on customerid id how to getting two files data
file1.txt data is:
[{'customerid':12,
'name':'xyz',
'email':'[email protected]'
},
{'customerid':14,
'name':'def',
'email':'[email protected]'
},
{'customerid':15,
'name':'pqr',
'email':'[email protected]'}
,{'customerid':17,
'name':'abc',
'email':'[email protected]'}]
file2.txt data is:
[{
' customerid':12,
'vachilenum':26789,
'price':390900920,
"phone":673648494894
},
{'customerid':14,
'vachilenum':26789,
'price':390900920,
"phone":673648494894
},
{'customerid':15,
'vachilenum':26789,
'price':390900920,
"phone":673648494894
},
{'customerid':17,
'vachilenum':26789,
'price':390900920,
"phone":673648494894
}];
i am trying this code but iam not getting expected out put any one please suggest me
const arr1 = fs.readFileSync('file1.txt', 'utf8').toString();
console.log(arr1)
const arr2 = fs.readFileSync('file2.text', 'utf8').toString();
console.log(arr2)
const merge = (arr1, arr2) => {
const temp = []
arr1.forEach(x => {
arr2.forEach(y => {
if (x.id === y.id) {
temp.push({ ...x, ...y })
}
})
})
return temp
}
console.log(merge(arr1, arr2))
expected outputt is
{'customerid':12,
'name':'xyz',
'email':'[email protected]'
'vachilenum':26789,
'price':390900920,
"phone":673648494894
},
CodePudding user response:
Try to use the map
function in combination with find
and return the merged object.
Also, you may wanna parse the file content to a JSON object:
const arr1 = JSON.parse(fs.readFileSync('file1.txt', 'utf8'));
console.log(arr1);
const arr2 = JSON.parse(fs.readFileSync('file2.text', 'utf8'));
console.log(arr2);
const merge = (arr1, arr2) => {
return arr1.map(x => {
const y = arr2.find(val => val.customerid === x.customerid);
if (!y) return x;
return { ...x, ...y }
})
};
console.log(merge(arr1, arr2));