Search code examples
javascriptreactjsarraysjavascript-objects

In an array of object, how to run other functions from inside map function?


newbie here. I have an array of objects from youtube api that looks like this :

const videoArray =
[{
  "kind": "youtube#playlistItem",
  "etag": "5_4yyrIK1DBbcLsSWOgtt5mHQrA",
  "id": "VVVjQWQ1TnA3Zk84U2VlakIxRlZLY1l3LnZmTGRHZGRHd093",
  "snippet": {
    "publishedAt": "2022-08-28T12:30:10Z",
    "channelId": "UCcAd5Np7fO8SeejB1FVKcYw",
    "title": "Central Vietnamese Street Food!! Noodles from Actual Heaven!!",
    "description": "🎥 SECOND CHANNEL!! MORE BEFRS »  \n👕 BEFRS MERCH » /ShopBEFRS\n💗 SUPPORT OUR MISSION » \n📷  CALVIN BUI’S IG » @fkndeliciousness | YouTube: https://youtube.com/c/FKNDeliciousness \n\nLike our music? Enjoy a free 30-day of Epidemic Sound for the best royalty-free music: http://share.epidemicsound.com/BEFRS \n- - - - - - - - - - - - - - - - -  \n1. TRADITIONAL CAO LAU NOODLE FACTORY \n\n🍜CAO LAU NOODLES: Soak the rice for 24 hours then grind it. Cook and stir until thick for 30 minutes.\nSteam for 30 minutes. Roll to make it flat and steam. \n- - - - - - - - - - - - - - - - -\n2. Quán Cao Lầu Bá Lễ\nADDRESS: 49/3 Trần Hưng Đạo, Sơn Phong, Hội An, Quảng Nam 56000\nOPENING TIME: 11AM - 8:30PM \n\n🍜CAO LAU: In a bowl, add herbs, bean sprouts, cao lau noodles, char siu, chả ram, deep fried pork fat (tốp mỡ) then meat sauce.\n\nPRICE: 35.000 VND / $1.51 USD \n- - - - - - - - - - - - - - - - -\n3. PHỞ SẮN FACTORY\n\n🍜 PHỞ SẮN: Grind the dried cassava into powder. Soak the cassava powder and water for 3 days and 3 nights then filter the water out, keeping the cassava powder. Whisk the cassava mixture in a pot for 30 minutes. Smooth mixture out. Place batter in a pressing machine. Dry noodles in the sun. After drying, cut into squares. \n- - - - - - - - - - - - - - - - -\n4. NHÀ HÀNG CỎ HỒNG\n\n🍜FRIED PHỞ SẮN: Pestle the pearl onions and place vegetables in hot water. Make the sauce with fish sauce, vinegar, msg, and coconut nectar. In a pan, add peanut oil. Fry the garlic, shrimp, and squid, add sugar, and then the vegetables. Add water and add a little starch. In another pan, deep-fry the pho san noodles. In a bowl, add the fried pho san, sauce, shrimp, squid, and top with spring onions.\n\n🍜PHỞ SẮN WITH FISH BROTH: Cook snakehead fish broth for 5 hours. Break the pho san into pieces and soak them in cold water for one minute. Place oil in a pot, add in pearl onions, garlic, tumeric, and the snakehead fish, and fry it for 10 minutes. Add in the pork. Pestle the fish. Add in the broth and cook\n- - - - - - - - - - - - - - - - -\n5. MÌ QUẢNG BÀ LÁNG\nADDRESS: Lê Thánh Tông street, An Phú ward, Tam Kỳ city, Quảng Nam Province\n\n🍜MÌ QUẢNG NOODLES: Soak the noodles and grind with a machine. Spread mixture on a flat surface and steam. When it’s cool, fold and cut it. \n\n🍜MÌ QUẢNG: Add fresh mì quảng in the bowl. Add char siu meat sauce. Add char siu and shrimp. Top with the peanuts and spring onions. Add herbs and fresh vegetables. \n\n#BEFRS #BestEverVietnamFoodTour #BestEverFoodReviewShow \n- - - - - - - - - - - - - - - - -\n💬COME SAY HI:\nINSTAGRAM »  (@besteverfoodreviewshow)\nFACEBOOK » \n \n💗SUPPORT OUR MISSION:\nPatreon is a platform that allows people to support creators on a recurring basis. Your contribution is an investment in the creative freedom of my channel and enables me to keep my content authentic and uninterrupted. Your donation allows me the time and resources to create more videos for you. We also have some pretty sweet rewards, exclusive to Patreon Bestys. » \n \nOur VIP Patrons: Susanne Smarr, Jim Klingsporn, Leo Lui, Sam Cassidy, Venetia Edmunds, Jack Murray, Eimile Nakoma, Jack Li, Stephen Balasta, Louis Chisari, Ryan Rhodes, Paul Citulski, Matthew Holden, David Baliles, Jackson Li, John Logan and Summer & Grayson Stumpf.  \n \n🥒 ABOUT BEFRS:\nHey, I’m Sonny! I’m from the US but I’ve been living in Asia for 10 years and started making food and travel videos to document my experiences. I travel to different parts of the world, hunting down and documenting the most unique food each country has to offer. \n \nIf you see any factual food errors in my videos, please feel free to politely let me know in the comments. I'm a huge fan of trying different, interesting foods in each country. My show is from a Western point of view, but more importantly, MY point of view. It is not meant to offend any person or culture. \n- - - - - - - - - - - - - - - - -\n🎬 CREDITS:\nHOST » Sonny Side\nDIRECTOR OF PHOTOGRAPHY » Nguyễn Tân Khải\nCAMERA OPERATOR » Tran Quang Dao\nVIDEO EDITOR » Thai Do \nCOLOR & MASTER » Quí Nguyễn\nPRODUCER » Nhi Huynh\n\nSelected tracks via Audio Network \nFor business inquiries: [email protected]",
    "channelTitle": "Best Ever Food Review Show",
    "playlistId": "UUcAd5Np7fO8SeejB1FVKcYw",
    "position": 0,
    "resourceId": {
      "kind": "youtube#video",
      "videoId": "vfLdGddGwOw"
    },
    "videoOwnerChannelTitle": "Best Ever Food Review Show",
    "videoOwnerChannelId": "UCcAd5Np7fO8SeejB1FVKcYw"
  },
  "contentDetails": {
    "videoId": "vfLdGddGwOw",
    "videoPublishedAt": "2022-08-28T12:30:10Z"
  }
},
{
... other similar object
}

I'd like to extract address from the description by splitting using the keyword 'ADDRESS : ' and push the result as key/value pair to the array of objects. Here's what I've been using :

let splitAddressResult = [];
let removeNoiseResult = [];
let extractAddressResult = [];

const splitAddress = (video) => {
    splitAddressResult = video.snippet.description.split("ADDRESS: ");
};
  
const removeNoise = (array) => {
    removeNoiseResult = array.map((element) => element.slice(1));
};
  
const extractAddress = (array) => {
    array.map((element) =>
      element.map((arr) => extractAddressResult = arr.split("\n")[0])
    );
    return extractAddressResult;
};

const getAdress = (videoList) => {
  videoList.map(function(video) {
    splitAddress(video);
    removeNoise(splitAddressResult);
    extractAddress(removeNoiseResult);
    video.push({address: extractAddressResult});
  });
};

getAddress(videoArray);

But it returns element.map is not a function. How do I solve this problem? Help is appreciated and thanks in advance!


Solution

  • Assuming that you want to pull just the address content from the snippet.description text, then you need to do more than split() by the ADDRESS: string.

    Firstly, split() the description by each line break, then filter() it to retrieve only the lines which start with ADDRESS:, then finally use map() and replace() to remove the ADDRESS: prefix.

    The logic would look like this:

    let getAddress = array => array
      .map(o => o.snippet.description.split(/\r?\n/)
      .filter(l => l.indexOf('ADDRESS:') === 0))  
      .flat()
      .map(l => l.replace(/^ADDRESS: /, ''));
    
    
    // irrelevant properties removed
    const videoArray = [{ snippet: { description: "\uD83C\uDFA5 SECOND CHANNEL!! MORE BEFRS \xbb  \n\uD83D\uDC55 BEFRS MERCH \xbb /ShopBEFRS\n\uD83D\uDC97 SUPPORT OUR MISSION \xbb \n\uD83D\uDCF7  CALVIN BUI’S IG \xbb @fkndeliciousness | YouTube: https://youtube.com/c/FKNDeliciousness \n\nLike our music? Enjoy a free 30-day of Epidemic Sound for the best royalty-free music: http://share.epidemicsound.com/BEFRS \n- - - - - - - - - - - - - - - - -  \n1. TRADITIONAL CAO LAU NOODLE FACTORY \n\n\uD83C\uDF5CCAO LAU NOODLES: Soak the rice for 24 hours then grind it. Cook and stir until thick for 30 minutes.\nSteam for 30 minutes. Roll to make it flat and steam. \n- - - - - - - - - - - - - - - - -\n2. Qu\xe1n Cao Lầu B\xe1 Lễ\nADDRESS: 49/3 Trần Hưng Đạo, Sơn Phong, Hội An, Quảng Nam 56000\nOPENING TIME: 11AM - 8:30PM \n\n\uD83C\uDF5CCAO LAU: In a bowl, add herbs, bean sprouts, cao lau noodles, char siu, chả ram, deep fried pork fat (tốp mỡ) then meat sauce.\n\nPRICE: 35.000 VND / $1.51 USD \n- - - - - - - - - - - - - - - - -\n3. PHỞ SẮN FACTORY\n\n\uD83C\uDF5C PHỞ SẮN: Grind the dried cassava into powder. Soak the cassava powder and water for 3 days and 3 nights then filter the water out, keeping the cassava powder. Whisk the cassava mixture in a pot for 30 minutes. Smooth mixture out. Place batter in a pressing machine. Dry noodles in the sun. After drying, cut into squares. \n- - - - - - - - - - - - - - - - -\n4. NH\xc0 H\xc0NG CỎ HỒNG\n\n\uD83C\uDF5CFRIED PHỞ SẮN: Pestle the pearl onions and place vegetables in hot water. Make the sauce with fish sauce, vinegar, msg, and coconut nectar. In a pan, add peanut oil. Fry the garlic, shrimp, and squid, add sugar, and then the vegetables. Add water and add a little starch. In another pan, deep-fry the pho san noodles. In a bowl, add the fried pho san, sauce, shrimp, squid, and top with spring onions.\n\n\uD83C\uDF5CPHỞ SẮN WITH FISH BROTH: Cook snakehead fish broth for 5 hours. Break the pho san into pieces and soak them in cold water for one minute. Place oil in a pot, add in pearl onions, garlic, tumeric, and the snakehead fish, and fry it for 10 minutes. Add in the pork. Pestle the fish. Add in the broth and cook\n- - - - - - - - - - - - - - - - -\n5. M\xcc QUẢNG B\xc0 L\xc1NG\nADDRESS: L\xea Th\xe1nh T\xf4ng street, An Ph\xfa ward, Tam Kỳ city, Quảng Nam Province\n\n\uD83C\uDF5CM\xcc QUẢNG NOODLES: Soak the noodles and grind with a machine. Spread mixture on a flat surface and steam. When it’s cool, fold and cut it. \n\n\uD83C\uDF5CM\xcc QUẢNG: Add fresh m\xec quảng in the bowl. Add char siu meat sauce. Add char siu and shrimp. Top with the peanuts and spring onions. Add herbs and fresh vegetables. \n\n#BEFRS #BestEverVietnamFoodTour #BestEverFoodReviewShow \n- - - - - - - - - - - - - - - - -\n\uD83D\uDCACCOME SAY HI:\nINSTAGRAM \xbb  (@besteverfoodreviewshow)\nFACEBOOK \xbb \n \n\uD83D\uDC97SUPPORT OUR MISSION:\nPatreon is a platform that allows people to support creators on a recurring basis. Your contribution is an investment in the creative freedom of my channel and enables me to keep my content authentic and uninterrupted. Your donation allows me the time and resources to create more videos for you. We also have some pretty sweet rewards, exclusive to Patreon Bestys. \xbb \n \nOur VIP Patrons: Susanne Smarr, Jim Klingsporn, Leo Lui, Sam Cassidy, Venetia Edmunds, Jack Murray, Eimile Nakoma, Jack Li, Stephen Balasta, Louis Chisari, Ryan Rhodes, Paul Citulski, Matthew Holden, David Baliles, Jackson Li, John Logan and Summer & Grayson Stumpf.  \n \n\uD83E\uDD52 ABOUT BEFRS:\nHey, I’m Sonny! I’m from the US but I’ve been living in Asia for 10 years and started making food and travel videos to document my experiences. I travel to different parts of the world, hunting down and documenting the most unique food each country has to offer. \n \nIf you see any factual food errors in my videos, please feel free to politely let me know in the comments. I'm a huge fan of trying different, interesting foods in each country. My show is from a Western point of view, but more importantly, MY point of view. It is not meant to offend any person or culture. \n- - - - - - - - - - - - - - - - -\n\uD83C\uDFAC CREDITS:\nHOST \xbb Sonny Side\nDIRECTOR OF PHOTOGRAPHY \xbb Nguyễn T\xe2n Khải\nCAMERA OPERATOR \xbb Tran Quang Dao\nVIDEO EDITOR \xbb Thai Do \nCOLOR & MASTER \xbb Qu\xed Nguyễn\nPRODUCER \xbb Nhi Huynh\n\nSelected tracks via Audio Network \nFor business inquiries: [email protected]" } }];
    let addresses = getAddress(videoArray);
    console.log(addresses);

    Note the use of flat() as well. This will mean that all addresses found in any of the objects within the original videArray will be flattened in to a single array response.