Home > Net >  How to navigate and assign value to a nested object in my Pinia store using typescript
How to navigate and assign value to a nested object in my Pinia store using typescript

Time:09-13

So I have a nested object stored in my Pinia store. It is something like this.

templateObj = {
    contents: [
        {
            'foo': 'AAA'
            'zoo': {
                'tee': {
                    'wee': "",
                    'alt': "",
                }
            }
        },
        {
            'foo': 'BBB'
            'moo': {
                'bee': {
                    'poo': {
                        'chi': "",
                        'rye': "",
                    }
                }
            }
        },
    ]
}

I have a variable that holds the information what part of the object I should be updating.

const mapStr = 'zoo.tee.wee'

My problem now is how can I navigate to that part and actually fill in the data.

My current solution below, was able to navigate to the part of the object, but its not updating its value.

In the actions of my Pinia store definition, I have this method.

actions: {
  setValueToTargetTemplateModule () {
    const srcMapStrArr = mapStr?.split('.')
    if (srcMapStrArr && moduleId !== undefined) { //moduleId is a state variable also that holds the index number of which content should be updated
      let templateProp  = this.templateObj?.contents[moduleId]
      for (const key of srcMapStrArr) {
        templateProp = templateProp[key]
      }
      templateProp = "Updated Value"
    }
  }
},

CodePudding user response:

You're changing the local copied value of the string wee, not the original object.

To fix this, you can stop one step before the last part and assign to templateProp the object that contains the property that you want to change (or, to be correct, a reference to this object, so when you change it, the original object will also change).

const a = { b: { c: { d: "" } } };
const path = "b.c.d".split(".");
let tmp = a;
for (const k of path) {
    tmp = tmp[k];
}
tmp = "e";
console.log(tmp); // "e"
console.log(a.b.c.d); // "", not changed

tmp = a; // let's try once again

for (const k of path.slice(0, path.length - 1)) {
    tmp = tmp[k];
}

tmp[path[path.length - 1]] = "e";
console.log(tmp); // "e"
console.log(a.b.c.d); // "e", changed

So:

actions: {
  setValueToTargetTemplateModule () {
    const srcMapStrArr = mapStr?.split('.')
    if (srcMapStrArr && moduleId !== undefined) { //moduleId is a state variable also that holds the index number of which content should be updated
      let templateProp  = this.templateObj?.contents[moduleId]
      for (const key of srcMapStrArr.slice(0, srcMapStrArr.length - 1)) {
        templateProp = templateProp[key]
      }
      templateProp[srcMapStrArr[srcMapStrArr.length - 1]] = "Updated Value"
    }
  }
},
  • Related