jhrmdk
jhrmdk

Reputation: 642

How to iterate over YAML config and get options?

I have this YAML config file:

sheets:
  list1:
    name: 'sheet1'
    sql: 'SELECT'
  list2:
    name: 'sheet2'
    sql: 'SELECT'
  list3:
    name: 'sheet3'
    sql: 'SELECT'

I use library 'js-yaml' for parsing YAML config. I want to for example console log all list names. How can I do this? I have something like this in JS:

for(sheet in config.sheets) {
    console.log(sheet.name);
}

when I do console.log(sheet) in loop i get list1, list2, list3 but console.log(sheet.name) in loop doesn't work.

Upvotes: 1

Views: 4267

Answers (1)

Navitas28
Navitas28

Reputation: 777

You should use a tool like js-yaml , to first convert your yaml to a js literal.

const yaml = require('js-yaml');
let data = yaml.load(config);

It will return the data like this:

 {
       sheets: {
          list1: {
           name: "sheet1",
           sql: 'SELECT'
        },
......other lists
     }
   }

then you can simply

const data = {
  sheets: {
    list1: {
      name: "sheet1",
      sql: 'SELECT'
    },
    list2: {
      name: "sheet2",
      sql: 'SELECT'
    }
  }
}

const name = Object.values(data.sheets).map(item => item.name)
console.log(values);

Upvotes: 2

Related Questions