JSON Object Properties Assignment

Asked 2 years ago, Updated 2 years ago, 76 views

For example, you want to store values on an object called db in the following structure:

db = {level1: { 0901 : { 1210: { data : 3.0}}}};

db = {}To save the above value when

db['level1'][0901']['1210']['data'] = 3.0 and the second

It says that the sub-item, or '0901' property, is not specified.

So I had to code it like this.

db = {};
db['level1'] = {};
db['level1']['0901'] = {};
db['level1']['0901']['1210'] = {};
db['level1']['0901']['1210']['data'] = 3.0

Is there a simpler way?

javascript node.js json

2022-09-21 19:21

3 Answers

It works like this.

  addDataArrayToDB(dataArray, fileName: string) {
    const fileInformation = this.findInfomationFromFileName(fileName);
    const sensorNumber = fileInformation.sensorNumber;
    const startingDate = fileInformation.startingDate;
    const startingTime = fileInformation.startingTime;

    this.flowDB = {
      [sensorNumber] : {
        [startingDate] : {
          [startingTime] : {
            'data' : dataArray[0]
          }
        }
      }
    };
    console.log(this.flowDB);
  }


2022-09-21 19:21

var db = {
    "level1": { 
        "0901" : { 
            "1210": { 
                "data" : 3.0
            }
        }
    }
};

I can just do it like this...

Is there a reason to create an object with a property approach expression?


2022-09-21 19:21

The pattern you want is usually described as a namespace pattern. Usually, if you pass only the name you want, you create a utility function that creates object chaining in that namespace. If you just type javascript namespace on Google, you will find a lot of Korean materials.


2022-09-21 19:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.