2

if I have an array of object like this

[{name: 'james', name: 'john'}] and I know the index of john and want to change the value of john I'll do

person = person.map((p, i)=>i===index?({...p, name: 'changed john'})):p) this.setState({person})

but what if the array is like this? ['james', 'john']

3
  • 1
    If you know the index of an item in an array, you don't need map, you just do person[index] = .... Commented Oct 19, 2018 at 2:05
  • 1
    if you have const arr = ['james','john'], then you just do arr[0] = 'Sam' and then you'll have ['Sam','john'] ... You don't need to map. Just use array indexes. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 19, 2018 at 2:05
  • 1
    If the values of items in the array are not directly changeable by array index then our answers won't work. This is more of a React state management issue than an array one isn't it? In that case, Nguyễn Thanh Tú answer is the right one. Commented Oct 19, 2018 at 2:30

4 Answers 4

1

but what if the array is like this? ['james', 'john']

Because the correct way to update state is using setState method, hence, the act of directly mutating state like this.state.list[i]="Changed John" won't work. I think that we just use Array.prototype.map() as usual. Like this:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: ['james', 'john']
    };
  }
  handleDelete = i => {
    const newList = this.state.list.filter((li, idx) => idx !== i);
    this.setState({ list: newList });
  };
  handleChange = i => {
    const newList = this.state.list.map(
      (li, idx) => (idx === i ? 'Changed ' + li : li)
    );
    this.setState({ list: newList });
  };
  render() {
    return (
      <div>
        {this.state.list.map((e, i) => (
          <div key={i}>
            <p>{e}</p>
            <button onClick={() => this.handleDelete(i)}>Delete</button>
            <button onClick={() => this.handleChange(i)}>Change</button>
          </div>
        ))}
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"><div>


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

2 Comments

map won't work if you have onChange on an input, where e.target.value is per character entered by the user.
@Melissa94 now then we see the input and onChange, the question should be updated cuz my answer doesn't intend to solve that
0

You want something like this?

person = person.map((p, i) => p === "john" ? "changed john" : p);

1 Comment

You might need to get index. let index = person.indexOf("john") person = person.map((p, i) => i=== index ? "changed john" : p);
0

It's pretty easy. Here you have examples for both situations:

const test = [{name: 'james', name: 'john'}];

// Here we're accessing the 1st element and its 'name' property
console.log(test[0].name);

// Here we're accessing the 2nd element.
// JavaScript arrays are zero-indexed: the first element of an array is at index 0

const test2 = ['james', 'john'];

console.log(test2[1])

I suggest visiting MDN docs for exploring other (all) examples.

Comments

0

person = person.map((p, i) => p === "john" ? "changed john" : p);

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.