0

I have this object:

let ob1 = {
  "2021-08-10": {
    "A0304": {
      "48": 1000
    },
    "A0301": {
      "4": 1000,
      "30": 1000,
      "40": 1000
    }
  },
  "2021-08-11": {
    "A0301": {
      "4": 1000
    }
  }
}

and I would like to insert another object like

"2021-08-13": {"A0301": {4: 1000}

using

let new =  {'2021-08-13': {'A0301': { 4: 'Hallo'}}}; 
Object.assign(obj1,new);`

works fine. But I would like to do it dynamic like:

 let new =  {app.desire.date: {app.desire.slot: { app.desire.slot: 'Hallo'}}}; 

But by defineing new I get the error: Uncaught SyntaxError: missing : after property id

How to do that right?

hamburger
  • 1,339
  • 4
  • 20
  • 41
  • 1
    You need to use square brackets (`[ ]`) to assign with dynamic keys: `let new = {[app.desire.date]: {[app.desire.slot]: { [app.desire.slot]: 'Hallo'}}}; ` – Harun Yilmaz Aug 13 '21 at 11:01

1 Answers1

1

Try using [app.desire.date]

let obj1   = {
  "2021-08-10": {
    "A0304": {
      "48": 1000
    },
    "A0301": {
      "4": 1000,
      "30": 1000,
      "40": 1000
    }
  },
  "2021-08-11": {
    "A0301": {
      "4": 1000
    }
  }
}

const newNode = { '2021-08-13': { 'A0301': { 4: 'Hallo' } } };
Object.assign(obj1, newNode);

var app = {
  desire: {
    date: '2021-08-14',
    slot: 'A0301',
    key: 4
  }
}

let newNode2 = {
  [app.desire.date]: {
    [app.desire.slot]: {
      [app.desire.key]: 'Hallo'
    }
  }
};

Object.assign(obj1, newNode2);
console.log(obj1)
Nitheesh
  • 19,238
  • 3
  • 22
  • 49