3

If i have an array like:

[
{ "user": "tom",
  "email": "[email protected]"
},
{ "user": "james",
  "email": "[email protected]"
},
{ "user": "ryan",
  "email": "[email protected]"
}
]

But it's not always being returned in that order - how can i check if ryan, for example, exists somewhere in one of these objects?

3 Answers 3

2

If you are already using lodash (or want to) then I would use its find:

_.find(array, { user: "ryan" })

Or with a few more characters you can do it without lodash:

array.find(elem => elem.user === "ryan")

Both return undefined if a matching element is not found.

Sign up to request clarification or add additional context in comments.

Comments

1

Function return true if array contains ryan.

var input = [
{ "user": "tom",
  "email": "[email protected]"
},
{ "user": "james",
  "email": "[email protected]"
},
{ "user": "ryan",
  "email": "[email protected]"
}
]
var output = input.some(function(eachRow){
    return eachRow.user === 'ryan';
});

console.log(output);

Comments

0

My method to solve that is to extract the targeted fields into arrays then check the value.

const chai = require('chai');
const expect = chai.expect;

describe('unit test', function() {
  it('runs test', function() {
    const users = [
      { "user": "tom",
        "email": "[email protected]"
      },
      { "user": "james",
        "email": "[email protected]"
      },
      { "user": "ryan",
        "email": "[email protected]"
      }
    ];
    const names = extractField(users, 'user'); // ['tom', 'james', 'ryan']   

    expect(names).to.include('ryan');
  });

  function extractField(users, fieldName) {
    return users.map(user => user[fieldName]);
  }
});

I'm using chai for assertion. In case you want to check in other fields, we just use the extract methods.

const emails = extractField(users, 'email');
expect(emails).to.include('ryan');

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.