Change Object Value using forEach

Issue

I am trying to change the value of object from the array but, it’s not work as expected. I tried following.

const arrObj = [
  {
    "label": "test1",
    "value": 123,
    "type": "number",
    "field": {
      "label": "another",
      "description": "abcd"
    }
  },
  {
    "label": "test2",
    "value": 111,
    "type": "number"
  },
]

arrObj.forEach(obj => {
  obj = {...obj, ...obj.field}
  delete obj.field
})

console.log("after:", arrObj);

Also I found some solution that to use index but, it add index before the object.

const arrObj = [
  {
    "label": "test1",
    "value": 123,
    "type": "number",
    "field": {
      "label": "abcd",
      "description": "abcd"
    }
  },
  {
    "label": "test2",
    "value": 111,
    "type": "number"
  }
]

arrObj.forEach((obj, index) => {
  obj[index] = {...obj, ...obj.field}
  delete obj.field
})

console.log("after:", arrObj);

How can I do with forEach?

Edit:

I want to remove the field object and assign/overwrite all the property outside.

Solution

Using map and assigning the result is probably a better way of doing this, but if you want to use forEach, you need to assign to the original array inside the loop:

const arrObj = [
  {
    "label": "test1",
    "value": 123,
    "type": "number",
    "field": {
      "label": "another",
      "description": "abcd"
    }
  },
  {
    "label": "test2",
    "value": 111,
    "type": "number"
  },
]

arrObj.forEach(({ field, ...rest}, idx, orig) => {
  orig[idx] = { ...rest, ...field }
})

console.log(arrObj);

Answered By – Nick

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published