我是 Nodejs 和 JSON 操作的新手。我有一个看起来像
"ent": [
{
"employee": [
{
"emp_name": "",
"column": "employee",
"emp_id": 123456,
"first name": "Joe",
"last name": "Bloggs",
"email": "",
"ldapid":
} ,
{
"emp_name": "",
"column": "employee",
"emp_id": 123456,
"first name": "Foo",
"last name": "Bars",
"email": "",
"ldapid":
}
]
}
]
我需要根据名字和姓氏填写电子邮件、ldapid 和 emp_name
所需的输出是
"ent": [
{
"employee": [
{
"emp_name": "Joe Bloggs",
"column": "employee",
"emp_id": 123456,
"first name": "Joe",
"last name": "Bloggs",
"email": "jbloggs@mycompemail.com",
"ldapid": "jbloggs"
} ,
{
"emp_name": "Foo Bars",
"column": "employee",
"emp_id": 567891,
"first name": "Foo",
"last name": "Bars",
"email": "fbars@mycompemail.com",
"ldapid": "fbars"
}
]
}
]
由于我对 nodeJS 世界非常陌生,因此我正在采取一些初步步骤来到达我想要的地方..
以下是我所做的..
编辑了我的帖子
大家好,感谢您的所有回复。我希望得到一个类似于下面的答案。这可能不是具有最佳实践的代码,但可以做到我想要的,也许这个小组的专家可以让它变得更好。
const fs = require('fs');
/** Method to start
*
*
*/
const main = async () => {
const myJSONObject = require('./people.json');
try {
for (var i = 0; i < myJSONObject.entities.length; i++) {
var entity = myJSONObject.entities[i];
if (entity.People) {
for (var j = 0; j < entity.People.length; j++) {
var people = entity.People[j];
var fn = people["first name"];
var ln = people["last name"];
var email = `${fn.substring(0, 3)}${ln.substring(0, 5)}@mycompmail.com`;
var ldapid = `${fn.substring(0, 3)}${ln.substring(0, 5)}`;
myJSONObject.entities[i].People[j]["email"] = email.toLowerCase();
myJSONObject.entities[i].People[j]["ldap id"] = ldapid.toLowerCase();
myJSONObject.entities[i].People[j]["preferred first name"] = fn;
myJSONObject.entities[i].People[j]["preferred last name"] = ln;
// console.log(`${fn}.${ln}`)
}
}
}
fs.writeFileSync('./new_people.json', JSON.stringify(myJSONObject, 0, 4));
}
catch (error) {
console.log(error);
}
};
(async () => {
await main();
})();
对此的任何帮助都将受到高度赞赏。瓦基恰克