【问题标题】:How to extract only certain fields from CSVTOJSON in nodejs?如何从nodejs中的CSVTOJSON中仅提取某些字段?
【发布时间】:2021-07-05 23:34:09
【问题描述】:

我已成功使用 csvtojson npm 包将 CSV 数据转换为 JSON,并成功在控制台中显示。

csvtojson()
      .fromFile(csvFilePath)
      .then(jsonObj => {
        console.log(jsonObj);
      })


[
  {
    id: '1',
    title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
    price: '109.95',
    description: 'Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday',
    category: 'men clothing',
    image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg'
  }
]

现在我只想控制台记录 id 和 title 字段,我应该怎么做?非常感谢,非常感谢任何帮助。再次感谢

【问题讨论】:

    标签: node.js csvtojson


    【解决方案1】:

    原因是:它是来自 console.log 值的对象数组。你可以这样做:

    console.log(`Id: ${jsonObj[0].id}` and Title: ${jsonObj[0].title})
    

    如果你有多个对象,你可以像这样循环遍历它:

    const jsonObj = [{
        id: '1',
        title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
        price: '109.95',
        description: 'Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday',
        category: 'men clothing',
        image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg'
      }, {
       id: '2',
        title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
        price: '109.95',
        description: 'Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday',
        category: 'men clothing',
        image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg'
      }]
    
    jsonObj.forEach(el => console.log(`Id: ${el.id}, title: ${el.title}`));

    【讨论】:

    • 嗨 Apoorva Chikara,非常感谢数组提示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2017-06-10
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多