Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!