0

For example I have a JSON data like

olddata = {
    userNname : "joeydash",
    sex : "female",
    email : "[email protected]"
};
dataToEdit = {
    name = "Mritunjoy Das",
    sex = "male"
};

Is there any function in javascript such that if i do

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

it shows

{
   userNname : "joeydash",
   name : "Mritunjoy Das"
   sex : "male",
   email : "[email protected]"
}
0

2 Answers 2

1

olddata = {
    userNname : "joeydash",
    sex : "female",
    email : "[email protected]"
};
dataToEdit = {
    name : "Mritunjoy Das",
    sex : "male"
};
var newData = Object.assign(olddata, dataToEdit);
console.log(newData);

Sign up to request clarification or add additional context in comments.

3 Comments

If you want to have a new object, created from olddata, you should use newData=Object.assign({},olddata,dataToEdit) instead. But even so, keep in mind that this will not be a "deep" copy.
You're right, but the author didn't asked for a deep copy
Pretty sure the author didn't ask for olddata to be overwritten.
1

Try this:

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

Also change = to : as:

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

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.