kirimi
kirimi

Reputation: 1400

How to update object value the right way

I am having issue updating my object's value.

I have an object that is structured like this:

const myObject =  {

      [_selectedDay] :
        {
        toDo:'workout',
        selected: true,
      }
  }

I have a button that adds my object and When I console.log my object I get this:

//I expaned [0]
(5) [{…}, {…}, {…}, {…}, {…}] "object"
0: 
->2019-06-03: {toDo: "workout", selected: true}
1: {2019-06-04: {…}}
2: {2019-06-05: {…}}
3: {2019-06-06: {…}}
4: {2019-06-07: {…}}

My question: Is it possible to update 2019-06-03's toDo field from workout to study?

I tried this code but won't work.

 myObject[0].toDo = 'workout'

Upvotes: 0

Views: 150

Answers (3)

jsadev.net
jsadev.net

Reputation: 2590

So at first we should take a look at this:

(5) [{…}, {…}, {…}, {…}, {…}] "object"
0: 
->2019-06-03: {toDo: "workout", selected: true}
1: {2019-06-04: {…}}
2: {2019-06-05: {…}}
3: {2019-06-06: {…}}
4: {2019-06-07: {…}}

myObject[0].todo is undefined because there is no .todo on myObject[0]. Furthermore ther is no .todo anywhere in your object. But theres a .toDo (D instead of d) on myObject[0]['2019-06-03'].

using myObject[0]['2019-06-03'].toDo = 'study' should work. :)


Off-topic: (to answer your comment):

This could be a solution if your data-structure should not be changed. Take a look at the comments inside the code:

var myObject = [
  {'2019-06-04': {toDo: 'study', selected: true}},
  {'2019-06-05': {toDo: 'workout', selected: true}},
  {'2019-06-06': {toDo: 'party', selected: true}},
  {'2019-06-07': {toDo: 'work', selected: true}}
];

function catchbydate(key) {
  // loop through your array:
  for(var i = 0; i < myObject.length; i++) {
    // return if objectkey was found:
    if(myObject[i].hasOwnProperty(key)) return myObject[i];
  }
  // otherwise return null:
  return null;
}

console.log(catchbydate('2019-06-06'));

Upvotes: 2

AshishAgrahari
AshishAgrahari

Reputation: 126

To answer your comment on J Sadi's answer, somehow in your code, your "myObject" is getting converted to array of objects and hence you have to access it via index, like myObject[0]. If your structure remains correct like below, you can directly access (or console.log) your property like myObject['2019-06-03'].

myObject =  {
      2019-06-03 :
        {
        toDo:'workout',
        selected: true,
      },
      2019-06-04 :
        {
        toDo:'study',
        selected: true,
      }
  }

now you can do console.log(myObject['2019-06-03']).

Upvotes: 1

Mamun
Mamun

Reputation: 68933

You can try using the first key:

var firstKey = Object.keys(myObject)[0];
myObject[firstKey].todo = 'workout'

Upvotes: 1

Related Questions