【问题标题】:forEach not a function javascriptforEach 不是函数 javascript
【发布时间】:2018-03-02 05:41:37
【问题描述】:

我正在尝试循环遍历 JSON 对象以从中提取数据。当我运行我的代码时,我得到了错误:

类型错误:element.listing.forEach 不是函数。

我还想指出,我之前在我的代码中已经完成了这项工作,并且效果很好。我已经尝试了forEach is not a function error with JavaScript array 上发布的解决方案。他们都没有工作。该字符串只是充满了空格。这是我的代码:

var JSONBody = JSON.parse(body);
var dataString = "";
var count = 0;

//Get required data from response body:
JSONBody.forEach(function(element) {
if(element.listing != null){
    element.listing.forEach(function (element2) {
        dataString = dataString + element2.media[0].url;
        dataString = dataString + "!!!";
        dataString = dataString + element2.propertyDetails.bedrooms;
        dataString = dataString + "!!!";
        dataString = dataString + element2.propertyDetails.bathrooms;
        dataString = dataString + "!!!";
        dataString = dataString + element2.propertyDetails.carspaces;
        dataString = dataString + "!!!";
        dataString = dataString + element2.propertyDetails.displayableAddress;
        dataString = dataString + "|||";

        //console.log(element2.media[0].url);
        count++;
    }, this);
    console.log(dataString);
    }else{
        dataString = "";
        console.log("Listings is NULL!");
    }
}, this);

JSONBody 看起来像:

[ { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11658083,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'Ultra Modern Furnished Apartment with Stunning Views',
       summaryDescription: '<b>Ultra Modern Furnished Apartment with Stunning Views</b><br />Brisbane\'s newest luxury complex \'Spire\' hits the market with huge popularity. Apartment 2704 offers the lucky resident the very best of the already stunning facilities and views with 27t...',
       hasFloorplan: false,
       hasVideo: false,
       labels: [Array],
       inspectionSchedule: [Object],
       listingSlug: '2704-550-queen-street-brisbane-city-qld-4000-11658083' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 8980993,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'High Floor with views in Parkland Paradise & Pet friendly\n',
       summaryDescription: '<b>High Floor with views in Parkland Paradise & Pet friendly\n</b><br />Lap up luxury living with the world’s largest inner-city sub-tropical parklands at your doorstep!! \r\n\r\n\r\n*\t3 good size bedrooms\r\n*\t2 bath rooms\r\n*\t1 car space\r\n*\t3 phone lines\r\n*\tFu...',
       hasFloorplan: true,
       hasVideo: false,
       labels: [],
       inspectionSchedule: [Object],
       listingSlug: '7054-7-parkland-blvd-brisbane-city-qld-4000-8980993' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11626727,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'STUNNING INNER CITY PARKLAND APARTMENT!',
       summaryDescription: '<b>STUNNING INNER CITY PARKLAND APARTMENT!</b><br />A gorgeous inner city apartment capturing stunning parkland views, this two bedroom executive apartment offers it\'s new tenant a fantastic inner city lifestyle!\r\nComfortable, local and convenient, per...',
       hasFloorplan: false,
       hasVideo: false,
       labels: [],
       inspectionSchedule: [Object],
       listingSlug: '3113-3-parkland-boulevard-brisbane-city-qld-4000-11626727' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11660275,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'ENJOY EXPANSIVE, UNINTERRUPTED VIEWS OVER THE BOTANIC GARDENS AND BRISBANE RIVER at ABIAN..!!',
       summaryDescription: 'ENJOY EXPANSIVE, UNINTERRUPTED VIEWS OVER THE BOTANIC GARDENS AND BRISBANE RIVER at ABIAN..!!<br />Presenting an exclusive opportunity to lease this rare three bedroom luxury apartment. For executive renters wanting to secure a large, sophistica...',
       hasFloorplan: false,
       hasVideo: false,
       labels: [Array],
       inspectionSchedule: [Object],
       listingSlug: '2702---140-alice-street-brisbane-city-qld-4000-11660275' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11660130,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'ABIAN - unprecedented luxurious lifestyle!!! LOCATION LOCATION LOCATION..',
       summaryDescription: '<b>ABIAN - unprecedented luxurious lifestyle!!! LOCATION LOCATION LOCATION..</b><br />A SCULPTURAL RIVERFRONT MASTERPIECE BY SUNLAND GROUP - this building has to be seen to be believed.\r\n\r\nThis HUGE 160SQM 3 bedroom apartment on the 23rd floor offers o...',
       hasFloorplan: false,
       hasVideo: false,
       labels: [Array],
       inspectionSchedule: [Object],
       listingSlug: '2302---140-alice-street-brisbane-city-qld-4000-11660130' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11660012,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'ABIAN BOTANIC GARDENS -BRISBANE\'S NEWEST BUILDING OFFERING WORLD-CLASS FACILITIES..!',
       summaryDescription: 'ABIAN BOTANIC GARDENS -BRISBANE\'S NEWEST BUILDING OFFERING WORLD-CLASS FACILITIES..!<br />Located in the most sought after residential quarter of the CBD, you will have immediate access to the Botanical Gardens, South Bank as well as the abundan...',
       hasFloorplan: false,
       hasVideo: false,
       labels: [Array],
       inspectionSchedule: [Object],
       listingSlug: '1601---140-alice-street-brisbane-city-qld-4000-11660012' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11658812,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'STUNNING 2 BED AT ABIAN BOTANIC GARDENS, $675 P/W..!',
       summaryDescription: '<b>STUNNING 2 BED AT ABIAN BOTANIC GARDENS, $675 P/W..!</b><br />This large two-bedroom apartment embraces sweeping views over the Botanical Gardens, Brisbane River, Kangaroo Point cliffs and South Bank.\r\n\r\nThe bedrooms are generous in proportion and e...',
       hasFloorplan: true,
       hasVideo: false,
       labels: [Array],
       inspectionSchedule: [Object],
       listingSlug: '1301---140-alice-street-brisbane-city-qld-4000-11658812' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11629051,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'ABIAN  Brisbanes new standard in luxury living!!',
       summaryDescription: '<b>ABIAN  Brisbanes new standard in luxury living!!</b><br />Enjoy uninterrupted views of the River City skyline, Botanical Gardens, Kangaroo Point Cliffs and South Brisbane. Positioned at the unrivalled location directly opposite the Botanic Gardens a...',
       hasFloorplan: false,
       hasVideo: false,
       labels: [],
       inspectionSchedule: [Object],
       listingSlug: '3103-140-alice-street-brisbane-city-qld-4000-11629051' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11578249,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'SWEEPING RIVER VIEWS- EXQUISITE APARTMENT LIVING! 3 BEDROOM APARTMENT - MERITON!',
       summaryDescription: '<b>SWEEPING RIVER VIEWS- EXQUISITE APARTMENT LIVING! 3 BEDROOM APARTMENT - MERITON!</b><br />Call Daleen on 0427 689 598 to arrange your inspection today!\r\n\r\nCentral CBD Location | River + City Views | Close to transport | Onsite Building Manager | Gym...',
       hasFloorplan: true,
       hasVideo: false,
       labels: [],
       inspectionSchedule: [Object],
       listingSlug: '501-adelaide-street-brisbane-city-qld-4000-11578249' } },
  { type: 'PropertyListing',
    listing:
     { listingType: 'Rent',
       id: 11657497,
       advertiser: [Object],
       priceDetails: [Object],
       media: [Array],
       propertyDetails: [Object],
       headline: 'AMAZING NEW WATER-VIEW APARTMENT AT ABIAN BOTANIC GARDEN IS NOW READY FOR RENT',
       summaryDescription: '<b>AMAZING NEW WATER-VIEW APARTMENT AT ABIAN BOTANIC GARDEN IS NOW READY FOR RENT</b><br />This spectacular brand-new home on 16th floor features 2 bedrooms, 2 bathrooms, master bedroom with walk in robe and ensuite, air conditioning, single lockup gar...',
       hasFloorplan: false,
       hasVideo: false,
       labels: [],
       inspectionSchedule: [Object],
       listingSlug: '--140-alice-street-brisbane-city-qld-4000-11657497' } } ]

【问题讨论】:

  • 在控制台中显示JSONBody
  • 什么身体,它看起来怎么样?比如一个数组`[1,2,3]`或者一个对象`{1:'potato', 2:'orange'}`
  • Body 是来自服务器的响应,最初是 JSON 字符串格式的字符串
  • 好吧,这根本没有帮助......我们需要知道实际的结构是什么。
  • 现在我们看到你有一个对象,而一个对象没有 forEach。没有理由循环它只是引用它。 EG:参考列表类型如下:JSONBody.forEach(function(element) { console.log(element.listing. listingType) })

标签: javascript json foreach


【解决方案1】:

JSONBody 是一个对象,而不是数组。因此,您可以使用Object.keys(返回一个键数组)和Array.prototype.forEach(您可以将3个参数传递给回调函数以获得更多控制:itemindexarray)对其进行迭代:

Object.keys(JSONBody).forEach(function(key, index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
});

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 2016-06-28
    • 2020-08-07
    • 1970-01-01
    • 2017-04-03
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多