Javascript 如何在JSON对象中添加多个值并获得更新的JSON文件
我有以下JSON文件Javascript 如何在JSON对象中添加多个值并获得更新的JSON文件,javascript,node.js,json,Javascript,Node.js,Json,我有以下JSON文件 var info = [{ "name" : "john", "address" : "32 street, london", "contact" : 123456 },{ "name" : "jeyy", "address" : "51 street, new york", "contact" : 987654321, "gender" : "male" },{ "name" : "rober
var info = [{
"name" : "john",
"address" : "32 street, london",
"contact" : 123456
},{
"name" : "jeyy",
"address" : "51 street, new york",
"contact" : 987654321,
"gender" : "male"
},{
"name" : "robert",
"address" : "14th street, birmingham",
"contact" : 456123789,
"gender" : "male"
},{
"name" : "carlos",
"address" : "89th street, manchester",
"contact" : 23456
},{
"name": "johnny",
"address": "6th street, Washington",
"contact": 23456
},{
"name": "jack",
"address": "4th street, VA",
"contact": 23456,
"gender": "male"
}
];
正如您所看到的,我在一些数组中缺少gender=male对象。如何将它们添加到丢失的对象中,而不将它们添加到已丢失的对象中。
另外,我如何获得新的更新文件 这将解决问题-
变量信息=[{
姓名:约翰,
地址:伦敦市第32街,
联系人:123456
},{
姓名:jeyy,
地址:纽约市第51街,
联系人:987654321,
性别:男
},{
姓名:罗伯特,
地址:伯明翰第14街,
联系人:456123789,
性别:男
},{
姓名:卡洛斯,
地址:曼彻斯特89街,
联系人:23456
},{
姓名:约翰尼,
地址:华盛顿第六街,
联系人:23456
},{
姓名:杰克,
地址:弗吉尼亚州第四街,
联系人:23456,
性别:男
}
];
info.forEache=>{
var t=Object.keyse;
如果“性别”的索引为-1
e、 性别='男性';
}
console.loginfo 在这里,我使用forEach遍历数组,并检查每个对象在gender属性中是否有值。如果没有,那么给它一个值
变量信息=[{
姓名:约翰,
地址:伦敦市第32街,
联系人:123456
},{
姓名:jeyy,
地址:纽约市第51街,
联系人:987654321,
性别:男
},{
姓名:罗伯特,
地址:伯明翰第14街,
联系人:456123789,
性别:男
},{
姓名:卡洛斯,
地址:曼彻斯特89街,
联系人:23456
},{
姓名:约翰尼,
地址:华盛顿第六街,
联系人:23456
},{
姓名:杰克,
地址:弗吉尼亚州第四街,
联系人:23456,
性别:男
}
];
info.forEachi=>{
如果!i.gender i.gender=男性;
};
console.loginfo 您可以在该对象上使用,找出哪个对象没有属性性别,然后迭代添加它并再次写回文件
下面是一段代码片段,可以帮助您入门
const fs = require('fs');
const util = require('util');
// Promisify fs api(s)
const readFileAsync = util.promisify(fs.readFile);
const writeFileAsync = util.promisify(fs.writeFile);
// IIFE to read the file, find the objects which has missing properties, add them and write them back
(async function() {
try {
const fileContents = await readFileAsync('data.json');
const fileData = JSON.parse(fileContents);
const remainingData = fileData.filter(x => !x.hasOwnProperty('gender'));
remainingData.forEach(x => x.gender = 'Male');
await writeFileAsync('data.json', JSON.stringify(fileData, null, 4));
} catch(err) {
console.log(`Failed because: {err}!`)
}
})();