2

I want to look in an array of objects if it contains a property and returns true if it found it, or false if it did not find it

An example of my array : this.realEstateProjectMotivation.realEstateProjectOnSales[0] which is worth :

[
  {
    "id": 30,
    "satisfied": false,
    "onSaleSince":"1 day"
  }
]

I would like to look in if realEstateProjectOnSales it contains onSaleSince and satisfied properties

how can I do it using Lodash or EcmaScript 2015 for example ?

3 Answers 3

2

You can use the in operator to check if a property exists in an object. You can loop the array with Array#some to find if at least one object contains the properties:

const arr = [
  {
    "id": 30,
    "satisfied": false,
    "onSaleSince":"1 day"
  }
];

const containsProps = (item) => 'onSaleSince' in item && 'satisfied' in item;

const is0Contains = containsProps(arr[0]);

console.log('is0Contains: ', is0Contains);

const isArrayContains = arr.some(containsProps)

console.log('isArrayContains: ', isArrayContains);

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

Comments

1

It easy to do with lodash#has method:

let hasProps = _.has(arr, '[0].satisfied') && _.has(arr, '[0].onSaleSince');

const arr = [
  {
    "id": 30,
    "satisfied": false,
    "onSaleSince":"1 day"
  }
];

let hasProps = _.has(arr, '[0].satisfied') && _.has(arr, '[0].onSaleSince');
console.log(hasProps);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Comments

0

var a = [{
  id: 30,
  satisfied: false,
  onSaleSince: "1 day"
}, {
  id: 30,
  satisfied: false,
  onSaleUntil: "1 day"
}];

console.log(
  'Does every object in array has both `id` and `satisfied`?',
  a.every(x => 'id' in x && 'satisfied' in x)
);

console.log(
  'Is there any object in array which has both both `id` and `onSaleUntil`?',
  a.some(x => 'id' in x && 'onSaleUntil' in x)
);

console.log(
  'Does every object in array has at least one property of `onSaleSince` and `onSaleUntil`?',
  a.every(x => 'onSaleSince' in x || 'onSaleUntil' in x)
);

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.