1

let's say I have an array

const defaultList = [
  {
    "name":"John",
    "last_name":"doe"
  },
  {
    "name":"Alice",
    "last_name":"Smith"
  }
]

I want using for loop to add new value online, so in the end it will look like this

const defaultList = [
      {
        "name":"John",
        "last_name":"doe",
        "online":"yes"
      },
      {
        "name":"Alice",
        "last_name":"Smith",
         "online":"no"
      }
    ]

I am using React Hooks and array is defined in this way, where later I fill it with data above:

const [defaultList, setDefaultList] = useState([]);

I would appreciate any idea how to do it?

Thank You!

2 Answers 2

1

You could use .map

const res = defaultList.map(el => ({ ...el, online: 'yes' })

const defaultList = [
  {
    name: 'John',
    last_name: 'doe'
  },
  {
    name: 'Alice',
    last_name: 'Smith'
  }
]

const res = defaultList.map(el => ({ ...el, online: 'yes' }))

console.log(res)


Or .forEach with Object.assign()

defaultList.forEach(el => {
  Object.assign(el, { online: 'yes' })
})

const defaultList = [
  {
    name: 'John',
    last_name: 'doe'
  },
  {
    name: 'Alice',
    last_name: 'Smith'
  }
]

defaultList.forEach(el => {
  Object.assign(el, { online: 'yes' })
})

console.log(defaultList)


..which is equivalent to the for..of loop

for (const el of defaultList) {
  Object.assign(el, { online: 'yes' })
}

const defaultList = [
  {
    name: 'John',
    last_name: 'doe'
  },
  {
    name: 'Alice',
    last_name: 'Smith'
  }
]

for (const el of defaultList) {
  Object.assign(el, { online: 'yes' })
}

console.log(defaultList)


The difference is that the first method creates the whole new array, while the others is mutating the original one

Sign up to request clarification or add additional context in comments.

1 Comment

The map approach is definitely the better choice :)
0

You can't have 2 two variables with the same name Firstly, set default state by:

const [list, setList] = useState(defaultList)

After change to new list, call setList

setList(newDefaultList)

Use list for what you want instead of defaultList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.