可以在javascript中使用JSON编辑JSON

时间:2017-11-04 14:06:44

标签: javascript json ecmascript-6

例如,我有一个像

这样的JSON数据
olddata = {
    userNname : "joeydash",
    sex : "female",
    email : "ae16b001@smail.iitm.ac.in"
};
dataToEdit = {
    name = "Mritunjoy Das",
    sex = "male"
};

javascript中是否有任何功能,如果我这样做

newData = doSomething(oldData,dataToEdit);
console.log(newData);

显示

{
   userNname : "joeydash",
   name : "Mritunjoy Das"
   sex : "male",
   email : "ae16b001@smail.iitm.ac.in"
}

2 个答案:

答案 0 :(得分:1)

试试这个:

function doSomething(oldData,dataToEdit){
     for (var key in dataToEdit) {
         if (dataToEdit.hasOwnProperty(key)) {
              oldData[key] = dataToEdit[key];       
         }
     }
     return oldData;
}

同时将=更改为:

dataToEdit = {
    name : "Mritunjoy Das",
    sex : "male"
};

答案 1 :(得分:1)

olddata = {
    userNname : "joeydash",
    sex : "female",
    email : "ae16b001@smail.iitm.ac.in"
};
dataToEdit = {
    name : "Mritunjoy Das",
    sex : "male"
};
var newData = Object.assign(olddata, dataToEdit);
console.log(newData);