2

I have an array of objects formatted like this:

{
  "_id": "590cbcd9bf2b9b18ab3c3112",
  "title": "",
  "content": "Create Notes Webapp",
  "checked": true,
  "listID": "590cbc61bf2b9b18ab3c3110"
},
{
  "_id": "590cfe5a86fe0908c560c2b0",
  "title": "A Note 01",
  "content": "My first note.",
  "checked": false,
  "listID": "590cbe15bf2b9b18ab3c3114"
}

Here is the code I have to update each item:

  onTextChange = (key, note, value) => {
    clearTimeout(timeoutID);
    switch (key) {
      default:
        break;
      case 'title':
        note.title = value;
        break;
      case 'checked':
        note.checked = value;
        break;
      case 'content':
        note.content = value;
        break;
    }
    var notes = this.state.notes;
    var id;
    for (var i in notes) {
      if (notes[i]._id === note._id) {
        notes[i] = note;
        id = i;
        break;
      }
    }
    this.setState({ notes }, () => { timeoutID = setTimeout(() => this.updateNote(this.state.notes[id]), 3000); });

  }

This is called like this:

onChange={(e, value) => this.onTextChange('title', note, value)}

Is there a better way than using that switch statement to update the specified item in the object? Also, is there a simpler method of scanning the array for the id than the for loop?

2
  • why do you use settimeout? If you want to run code after the setState finishes do this: setState({notes}, ()=>{//your code}) Commented May 5, 2017 at 23:14
  • Good point actually. I forgot I should set the timer on the setState callback Commented May 6, 2017 at 2:18

3 Answers 3

1

Is there a better way than using that switch statement to update the specified item in the object?

You can use this syntax to update the note object. This also makes sure it does not insert new properties into note.

if (note.hasOwnProperty(key) {
  note[key] = value
}

For a cleaner syntax to update notes you could do

var newNotes = this.state.notes.map(n => n._id === note._id ? note : n);
this.setState({notes: newNotes});

This will create a newNotes array which is identical to the current state except it will replace the one where the passed in ._id is equal to the one in the array.

You would also have to adjust the updateNote call because you no longer save the index but you could probably just use the note variable?

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

1 Comment

or if (key in note).
1

instead of switch you can do this but you have to check if it exists in the object.

 onTextChange = (key, note, value) => {
clearTimeout(timeoutID);
if(note[key]){
    note[key] = value;
}
var notes = this.state.notes;
var id;

}

As for looping it is preferred by most standard like airbnb and google. if you want a better way you can do several things with that array of objects depending on the situation and if you're using es5, es6, but your options are: 1. Make array of objects into an object with key (property name) be your id (they can be any strings). 2. if es6 is used you can convert into map and it makes it so much lighter and faster to get needed object.

hope that helps.

Comments

1

Just as noveyak said, you can access properties in Javascript by using the bracket syntax, where the key is a string containing the name of the property (as you have it now).

Javascript has several different ways of accessing object properties:

note[key] = value;

// if key is 'title', it will be the same as:
note.title = value;

// also the same as:
note['title'] = value;

For your second question, instead of looping over an array, you can store those objects in another object with the id as the property value (essentially using it as a map). This way you can directly access the note entries by id. For example:

allNotes = {}; // create a new object
someNotes = {
 'title': '',
 'content': 'Create Notes Webapp',
 'checked': true,
 'listID': '590cbc61bf2b9b18ab3c3110'
};
allNotes[idOfNote] = someNote; // where idOfNote holds the actual id of the note as a string

You can read more about Javascript property accessors on Mozilla's reference website here.

Javascript also has proper maps you can use instead of an object, which is safer and faster if you're allowed to use ES2015. You can learn about it here (also Mozilla docs).

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.