Trouble with objects and assigning keys with variables

I’m trying to write a script that grabs uncompleted tasks from a list along with the project title (which is the markdown header). I wrote the following script in a very simple way and got a good result:

let stuff = "## 😀k-ey"
let x = stuff.replace("## ","")
let output = {[x]:[]}
alert(JSON.stringify(output))
let y = "value"
output[x].push(y)
alert(JSON.stringify(output))

However, with the complete script, I get an error saying that output[x].push is undefined. But the alerts show that the data I expect is being saved properly and that the object is officially an object.

var yesterdayNote = `# Top of File

## Project A
Descriptive line

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec finibus elit non nibh lobortis molestie.

- [ ] an undone task
- [x] a completed task
- [x] second completed task

## Project B
Descriptive line

- [x] a completed task
- [ ] an uncompleted task

## Project C
Descriptive line

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec finibus elit non nibh lobortis molestie.

- [x] completed task
- [ ] uncompleted task
- [x] completed task`;

var oldUndone = yesterdayNote.match(/## (.*)|- \[ \] (.*)/g)

var output = [];
var i=0;
while (i < oldUndone.length) {
    if (oldUndone[i].match(/## (.*)/g) && oldUndone[i] !== "## Practice" && oldUndone[i] !== "## Work"){
        let x = oldUndone[i].replace("## ","")
		output.push({[x]:[]})
    var q = 1;
    while (q < oldUndone.length){
        if (oldUndone[q].match(/- \[ \] (.*)/g)){
            let y = oldUndone[q].replace("- [ ] ","")
            alert("project push" + JSON.stringify(output) + "\n" + x + "\n" + y)
            if (
    typeof output === 'object' &&
     output !== null
) {
    alert("object")
}
else {
alert("not an object")
}

            output[x].push(y)
            q+=1
        }
    }
    }
    i += 1;
}
console.log(JSON.stringify(output))

I didn’t try to run this yet, but that catches my eye. Normally I would expect an object to have keys. In that case, you are using an array to define a key.

I would expect your object to be defined like { x: [] }, where “x” is the string key, then you would access that like, output[x].push(y) (note no brackets around they key.

yeah, it runs in my sample code fine though, and there’s this describing that:

from the doc:

const items = ["A", "B", "C"];
const obj = {
  [items]: "Hello",
};
console.log(obj); // A,B,C: "Hello"
console.log(obj["A,B,C"]); // "Hello"

ok, further testing reveals the issue. The above works fine. However, this does not work:

let stuff = "## 😀k-ey"
let x = stuff.replace("## ","")
let output = []
output.push({[x]:[]})
alert(JSON.stringify(output))
let y = "value"
output[x].push(y)
alert(JSON.stringify(output))

The difference is that I’m pushing an object to an array vs. creating the object.

1 Like