skip to Main Content

Sadly I cannot change the data that I receive. So I found a way around it but I feel like it’s a bit messy.

Here is an example of the data that I am working with:

var x = {
    // a simple array, we like these.
    data1: ['this', 'that', 'other'],
    
    // I don't know why it's like this, and I can't change it
    data2: [ {name:'joe'}, {name:'john'} ]
}

the goal is to run a bit of code if data1 or data2 have the name: joe.

if( x.data1.includes('joe') || x.data2.includes('joe') ){...}

Obviously, the second condition would not work with the data.

I turned to format data2 into a simple array with a function:

var formatData2 = function(){
    var arr = [];
    for( i in x.data2 ){
        arr.push( x.data2[i].name );
    }
    return arr;
}

This then lets me use this logic:

if( x.data1.includes('joe') || formatData2().includes('joe') ){...}

The question is:

Can I avoid formatting data2 into an array to check the values in an if statement?

var x = {
    data1: ['this', 'that', 'other'],
    data2: [ {name:'joe'}, {name:'john'} ]
}

var formatData2 = function(){
    var arr = [];
    for( i in x.data2 ){
        arr.push( x.data2[i].name );
    }
    return arr;
}

if( x.data1.includes('joe') || formatData2().includes('joe') ){
    console.log( true );
}

2

Answers


  1. You can use the some() method.

    if (x.data1.includes('joe') || x.data2.some(el => el.name == 'joe'))
    

    BTW, your formatData2() function can be simplified using map()

    function formatData2(x) {
        return x.data2.map(el => el.name);
    }
    
    Login or Signup to reply.
  2. You can use some() to loop over the array of objects and will return true when the condition is met.

    var x = {
        data1: ['this', 'that', 'other'],
        data2: [ {name:'joe'}, {name:'john'}, ],
    };
    
    const result = x.data1.includes('joe') || x.data2.some(({name})=> name === 'joe');
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search