Object.assign() for replacing objects of a json

object.assign deep copy
modifying a copy of a javascript object is causing the original object to change
object.assign array
object.assign polyfill
javascript add object to another object
javascript copy object without reference
object.assign javascript w3schools
javascript deep copy object

I have JSON looks like this:

{
"ArrayInfo": [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
]
}

I want to replace an object of JSON with another object.For example I have this object :

{"name":"E","Id":"5"}

and it is going to be replaced by this object of JSON:

{"name":"B","Id":"2"}

JSON should look like this :

{
"ArrayInfo": [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "E",
        "Id": "5"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
]
}

What I did is to use Object.assign but the new object will be added to array instead of replacing. (all the data is going to be dynamic but for making more understandable I use static data)

const itemToReplace = { "name": "E", "Id": "5" };
const prevItem = ArrayInfo[2]
ArrayInfo = ArrayInfo.map((el, idx) => {
  return Object.assign({}, el, { prevItem: itemToReplace });
});
let NewArryInfo = ArrayInfo
console.log(NewArryInfo)

The result of console.log(NewArryInfo) :

{
"ArrayInfo": [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
    {
        "name": "E",
        "Id": "5"
    }
]
}

You can use Array.prototype.splice to replace an item in Array.

const replaceItem = {"name":"E","Id":"5"}
const ArrayInfo = [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
];
ArrayInfo.splice(1, 1, replaceItem); // remove second item and replace
console.log(ArrayInfo);

How to set value to json object from another json object?, : var b = [ {id: "Make", field: "make", seqNo: a[0]. seqNo}, {id: "Model", field: "model", seqNo: a[1]. seqNo}, {id: "XModel", field: "model", seqNo: a[2]. The Object.assign () method only copies enumerable and own properties from a source object to a target object. It uses [ [Get]] on the source and [ [Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

const object = {
  "ArrayInfo": [{
      "name": "A",
      "Id": "1"
    },
    {
      "name": "B",
      "Id": "2"
    },
    {
      "name": "C",
      "Id": "3"
    },
    {
      "name": "D",
      "Id": "4"
    }
  ]
};

const objectToReplace = {
  "name": "B",
  "Id": "2"
};

const updatedObject = Object.assign({}, object, {
  ArrayInfo: object.ArrayInfo.map((info) => {
    if (info.Id === objectToReplace.Id && info.name === objectToReplace.name) {
      return {
        "name": "E",
        "Id": "5"
      };
    }

    return info;

  })
});

console.log(updatedObject);

Object.assign(), The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. b: { c: 0}}; let obj2 = Object.assign({}, obj1); console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}} obj1.a  The JSON becomes a custom object with nested objects, so really it is fairly simple. To start, let's fix the JSON by adding a comma after the Apples value, and convert it to an object

const myArr = [
    {
        "name": "A",
        "Id": "1"
    },
    {
        "name": "B",
        "Id": "2"
    },
    {
        "name": "C",
        "Id": "3"
    },
    {
        "name": "D",
        "Id": "4"
    }
];


const replaceObj = (arr, objReplaced, objToReplaceWith) => {
  const replacedObjIndex = arr.findIndex(item => JSON.stringify(item) === JSON.stringify(objReplaced));
 arr[replacedObjIndex] = objToReplaceWith;
 console.log(arr)
 return arr;
}

replaceObj(myArr, {"name":"B","Id":"2"}, {"name":"E","Id":"5"});

Object.assign() in JavaScript?, Background. Object.assign() copies the values (of all enumerable own properties​) from one or more source objects to a target object. It  Object.assign will only work in single level of object reference. To do a copy in any depth use as below: let x = {'a':'a','b':{'c':'c'}}; let y = JSON.parse(JSON.stringify(x)); If want to use any library instead then go with the loadash.js library.

When you map over the array you could check if each item is the one you want to replace, and if it is, return the new item instead.

ArrayInfo = ArrayInfo.map((el, idx) => {
  if (el.id === prevItem.id && el.name === prevItem.name) {
    return itemToReplace;
  }
  return el;
});

How to deep clone a JavaScript object, Alternatively, Object.assign is in the official released and will also create a shallow copy JSON replace function with null and function in object with undefined  JSON objects are surrounded by curly braces {}. JSON objects are written in key/value pairs. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon. Each key/value pair is separated by a comma.

Try this!

let ArrayInfo = [{"name": "A","Id": "1"},{"name": "B","Id": "2"},{"name": "C","Id": "3"},{"name": "D","Id": "4"}];
const onReplace = {"name":"E","Id":"5"};
const toReplace = {"name": "B","Id": "2"};

function replaceArray(array, onReplace, toReplace) {
  const removeIndex = array.map(item => { return item.name; }).indexOf(toReplace.name);
  array.splice(removeIndex, removeIndex, onReplace);
  return array
}

console.log(replaceArray(ArrayInfo, onReplace, toReplace));

ES6 Object.assign() Sample, We call the copy shallow because the properties in the target object can still hold JSON format does not support functions, therefore they are just removed altogether. describe('assign v1 (copy props)', () => { it('assigns objects This function works like assign but instead of replacing properties in the  Using Object.assign() method. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. let obj = {a: 1, b: 2,}; let objCopy = Object. assign ({}, obj); console. log (objCopy); // Result - { a: 1, b: 2 } ** ---> Edit on JS Bin ** Well, this does the job so far. We

3 Ways to Clone Objects in JavaScript, assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]]  Nevertheless, I included it in the test so you can run it in the future 😝. But the result shows Object.assign is a lot faster than JSON. Performance Test # Community Input # Object.assign vs Spread. @d9el: It's important to note that Object.assign is a function which modifies and returns the target object. In Samantha's example using the

4 different techniques for copying objects in JavaScript, objectNested }; // ~deep copy copyJSONparseNested JS | JS ES6+ | jQuey | Lodash | AngularJS Object.assign() Spread operator $.extend() .merge() It is a jQuery function that will extend and replace similar keys. As we know, JSON is usually helping us exchanging the data from the client-side to a remote server. So, when we have the JavaScript data in the Object form, it has to be in the string form to be sent to the webserver. Exactly that is where JSON.stringify() method comes in handy, It converts JavaScript simple or complex objects into a JSON string.

Object.assign( ) in JavaScript, But before that just keep one thing in mind that javascript objects are mutable by The Object.assign() method can be used to copy the values of all let copyOA = Object.assign({}, obj); console.log(JSON.stringify(obj)); // { a:  Using the spread syntax or Object. assign () is a standard way of copying an object in JavaScript. Both methodologies can be equivalently used to copy/merge the enumerable properties of an object to another object. Problem with these two approaches is that it will just do the shallow copy. A shallow copy is a bit-wise copy of an object.

Comments
  • Your question does not seem related to react but raw javascript. You might want to change your title and tag to get more answers.
  • There's no such thing as a "JSON Object". Is it a JSON formatted string or a JavaScript object!
  • ´Object.assign´ works that way, you can read here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… You can use ´splice´ instead.
  • It is a JSON Object.
  • Either it is JSON or an Object Literal, "JSON Object" is not a thing.
  • Thanks @Antonio for your answer. Could you please explain what are the numbers splice(1, 1 .. in splice mean?
  • First 1 is for second item, and second 1 is the number of items to be deleted, :)
  • @Maya Read the documentation.
  • Thanks @Antonio it's working :D
  • Thank @Nicolae Maties for your reply it was helpful :)