'Change Object Value using forEach

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 1:[1]

I would use map to change an array, but you may have a reason that you wish to modify the original. You could just reassign arrObj to the output of the map.

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

const newArr = arrObj.map(( obj ) => {
 const {field, ...rest} = obj
 return {...field, ...rest}
})

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Kerr