Creating condition inside the javascript map function

Asked

Viewed 67 times

-1

I have two problems related to the map/filter function.

I’m taking data from a google data tructure and they follow the schema.org, however, in my case, a specific information is not always in the array of the element I’m using to make the map(), more clearly:

  • All elements have the.title item, the.link item and the.snippet item
  • Not all elements have the item.pagemap.localbusiness

The first problem is that localbusiness is an array of objects, so I wasn’t able to get the elements from it directly, so I thought I’d use the following code:

placesInfo = response.data.items.map((item) => {
    return {
        title: item.title,
        link: item.link,
        snippet: item.snippet,
        // metatags: item.pagemap.metatags,
        // ratings: item.pagemap.aggregaterating
        localbusiness: item.pagemap.localbusiness.reduce((items) => { items.item }),
    }})

placesInfoMap = placesInfo.map((item) => {
    return {
        title: item.title,
        link: item.link,
        snippet: item.snippet,
        name: item.localbusiness.name,
        email: item.localbusiness.email,
        telephone: item.localbusiness.telephone,
        address: item.localbusiness.address
    }
})

An example of what this function returns in the console.log():

{title: 'Barbeshop - Curso de Barbeiro Elite',
link: 'https://business.google.com/website/barbeshop-curso-de-barbeiro-elite',
snippet: 'Barbeshop - Curso de Barbeiro Elite. Aberto hoje até 20:00. Solicitar cotação\n' +
  'Ligar ... Lucas Evangelista de Oliveira Franco, 45A - Aterrado. Volta Redonda - \n' +
  'RJ.',
name: 'Barbeshop - Curso de Barbeiro Elite',
email: undefined,
telephone: undefined,
address: 'Avenida Lucas Evangelista de Oliveira Franco, 45A - AterradoVolta Redonda - RJ27215-070Brasil'},

Response.data.items returns an array with elements like this:

{
    kind: 'customsearch#result',
    title: 'Restaurante 41 - Restaurante em Vila Santa Cecília',
    htmlTitle: '<b>Restaurante</b> 41 - <b>Restaurante</b> em Vila Santa Cecília',
    link: 'https://business.google.com/website/restaurante41',
    displayLink: 'business.google.com',
    snippet: 'Sou de Minas Gerais estivemos em volta redonda e almoçamos neste otimo \n' +
      'restaurante muito bom comida Boa atendimento bom ..gostamos. - Luciano s.',
    htmlSnippet: 'Sou de Minas Gerais estivemos em <b>volta redonda</b> e almoçamos neste otimo <br>\n' +
      '<b>restaurante</b> muito bom comida Boa atendimento bom ..gostamos. - Luciano s.',
    cacheId: 'p-eg18u63BsJ',
    formattedUrl: 'https://business.google.com/website/restaurante41',
    htmlFormattedUrl: 'https://business.google.com/website/<b>restaurante</b>41',
    pagemap: {
      cse_thumbnail: [Array],
      metatags: [Array],
      cse_image: [Array],
      localbusiness: [Array]
    }
  },

That way I was able to remove the elements of localbusiness right after the first map and reassemble the array I wanted, but I realized that when I tested with other data that did not contain localbusiness, the code broke.

My idea was to try to use an if function inside the map but I don’t know if it’s possible... I believe there may be better ways to do what I did without all this skulking...

Another problem is that this data is generated as json and I’m turning it to csv at the end of everything, so even when the map doesn’t find the name, email, Telephone and Adress I needed these values to be filled at least as a blank or null field and I don’t know how to guarantee that these values will be filled in, because the example above, in json that I Gero stays that way:

{"title":"Barbeshop - Curso de Barbeiro Elite","link":"https://business.google.com/website/barbeshop-curso-de-barbeiro-elite","snippet":"Barbeshop - Curso de Barbeiro Elite. Aberto hoje até 20:00. Solicitar cotação\nLigar ... Lucas Evangelista de Oliveira Franco, 45A - Aterrado. Volta Redonda - \nRJ.","name":"Barbeshop - Curso de Barbeiro Elite","address":"Avenida Lucas Evangelista de Oliveira Franco, 45A - AterradoVolta Redonda - RJ27215-070Brasil"}

That is, the email and Telephone were not filled.

I hope you can understand and hope someone saves me!

  • what returns: response.data.items

  • I updated the post because I could not put everything here in the comment

  • is because the die is a array do you understand? then if you’re going to take any position?

  • example: telephone: item.localbusiness[0].telephone,? maybe that’s it. I don’t know what’s inside item.localbusiness?

  • So, in case I’m taking the title, link, snippet and pagemap.localbusiness but I need to get things out of localbusiness and already add in the main array, I even managed to reassemble something now but when pagemap.localbusiness does not exist the break code

  • Arthur you need to put everything that can happen! just this I can’t answer!

  • name: item.pagemap.localbusiness.map((item) => { Return item.name }), email: item.pagemap.localbusiness.map((item) => { Return item.email }), Telephone: item.pagemap.localbusiness.map((item) => { Return item.Telephone }), address: item.pagemap.localbusiness.map((item) => { Return item.address }), I added these maps to placesInfo and deleted placesInfoMap but the code keeps breaking qnd n has localbusiness

  • yes that’s a array: item.pagemap.localbusiness.map! I know that but, I don’t know your goal

  • "localbusiness":[{"name":"Janaina Hairdrreira"}] Inside local business is like this, not all fields are filled and sometimes there is no localbusiness

  • you need to test if the key exists and so on to then assemble your object list

  • How would I do that? I tried to throw an if inside the map but it didn’t work

  • I got it, I made it work, thanks man! You saved me!!!!

Show 7 more comments

1 answer

0


A minimal example where you first search for the object’s key to then associate its value or null for a particular key:

const isExist = (obj, name) => {
  return Object.keys(obj).includes(name);
}

const arr = [
  { name: 't 1', item: { source: 1 }},
  { name: 't 2', item: {  }},
  { name: 't 3', item: {  }}
]

const b = arr.map(m => {
  return {
    name: m.name,
    item: isExist(m.item, 'source') ? m.item.source: null
  }
});

console.log(b);

and in that case whether source there is if yes takes the value of it if it does not pass null, and so successively must be done where the value may or may not exist.

Reference: Filter Object properties by key in ES6

  • 1

    All right, thank you very much! I had done something close to that but the way you made it simpler, I’ll try to implement!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.