Iterate over array list jquery and then make some changes in object properties .Create a new array list after changes

I have an array list and i am iterating over it using jquery map .while iterating i want to make changes to object properties and create a new array list . Any suggestion,idea ,help will be appreciated .

This is ‘m.data’ in console -> Array(10)

Now what I want to achieve is iterating over data and changing object[0].Name to something else and then again create final ‘new Array’ after changes in object properties

let m = {   data: [    {Id: 600, Name: "rety", Description: "ssa", Number: 135, type: "meter"},    {Id:624, Name: "xyz", Description: null, Number: 134, type: "PC"},    {Id: 645, Name: "abcd", Description: null, DNumber: 142, type: "pcs"},    {Id: 664, Name: "dfdf", Description: null, Number: 134, type: "PC"}   ] };  var _newarray = $.map(m.data, function(i, obj) {   for (var prop in obj) {     //I WANT TO MAKE CHANGES TO OBJ.NAME SAY AND AGAIN MAKE A NEW ARRAY   } });

Add Comment
2 Answer(s)

Please check this https://api.jquery.com/jQuery.map/. As it says in callback function it will have first parameter as object and second as index.

let m = {   data: [    {Id: 600, Name: "rety", Description: "ssa", Number: 135, type: "meter"},    {Id:624, Name: "xyz", Description: null, Number: 134, type: "PC"},    {Id: 645, Name: "abcd", Description: null, DNumber: 142, type: "pcs"},    {Id: 664, Name: "dfdf", Description: null, Number: 134, type: "PC"}   ] };  // set property name into object to updte dynamical property let propName = 'Name';  var _newarray = $.map(m.data, function(obj) {   // copy object with Object.assign   let newObj = Object.assign({}, obj);   // update required property. Use propName to set property   newObj[propName] = 'new value - ' + obj[propName];   // return object   return newObj; });  console.log(_newarray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Answered on July 16, 2020.
Add Comment

You don’t need to use map, just use for-of.

list1 = [{name: "item1"}, {name: "item2"}] list2 = []  for(const item of list1) {   new_item = Object.assign({}, item);    new_item.name = item.name+"-modified"   list2.push(new_item) }  console.log(list1) console.log(list2)

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.