如何在JSON对象中添加多个值并获取更新的json文件

时间:2019-01-11 10:41:42

标签: javascript node.js json

我有以下JSON文件

vuex

如您所见,我在某些数组中缺少“ gender” =“ male”对象。如何将它们添加到丢失的对象中,而不将它们添加到已经拥有的对象中。 另外,我将如何获取新的更新文件。

3 个答案:

答案 0 :(得分:0)

这将解决-

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"
}
];

info.forEach((e)=>{
    var t=Object.keys(e);
   
   if(t.indexOf('gender')==-1)
   e.gender='male';
})
console.log(info);

答案 1 :(得分:0)

在这里,我使用forEach()遍历数组,并检查每个对象在gender属性中是否具有值。如果没有,则给它一个值“ male”。

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"
}
];

info.forEach(i => {
  if(!i.gender) i.gender = "male";
});
console.log(info);

答案 2 :(得分:0)

您可以在该对象上使用.hasOwnProperty来找出哪个对象不具有属性gender,然后反复添加该对象并再次写回到文件中!


以下代码段可帮助您入门。

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}!`)
    }
})();