0

我已经设法使用 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 字段,我应该怎么做?非常感谢,非常感谢任何帮助。再次感谢

4

1 回答 1

3

原因是:它是来自 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}`));

于 2021-07-05T05:58:54.457 回答