27

I have an array of objects like this:

[ {"name": "apple", "id": "apple_0"}, 
  {"name": "dog",   "id": "dog_1"}, 
  {"name": "cat", "id": "cat_2"}
]

I want to insert another element, also named apple, however, because I don't want duplicates in there, how can I use lodash to see if there already is an object in the array with that same name?

2
  • 1
    ARRAY.find(function(el){ return el.name === 'apple'; }) If undefined, There is no element in array having name as "apple"
    – Rayon
    Oct 19, 2016 at 17:36
  • 3
    @reectrix _.has(object, path) Apr 28, 2018 at 18:09

7 Answers 7

50

You can use Lodash _.find() like this.

var data = [ {"name": "apple", "id": "apple_0"}, 
  {"name": "dog",   "id": "dog_1"}, 
  {"name": "cat", "id": "cat_2"}
]

if(!_.find(data, {name: 'apple'})) {
  data.push({name: 'apple2'});
}
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Reference documentation: https://lodash.com/docs/4.17.14#find

2
  • 3
    Link for _.find() documentation: https://lodash.com/docs/#find
    – dalcam
    Jul 30, 2018 at 3:06
  • this is not checking if property exists, but assumes property exists, and checks if has correct value. Wrong answer. Though a confusing question, guy asks one thing and then explains another
    – Dmitry
    Sep 13, 2019 at 14:43
14

This is Form

_.has(object, path)

Example:

const countries = { country: { name: 'Venezuela' } }
const isExist = _.has(countries, 'country.name')
// isExist = true

For more information Document Lodash

1
  • 7
    _.has tells about whether that path exists or not AND NOT about the value. Aug 17, 2018 at 8:02
5

You can use Array.prototype.find() or lodash's _.find():

const addItem = (arr, item) => {
  if(!arr.find((x) => x.name === item.name)) { // you can also change `name` to `id`
    arr.push(item);
  }
};

const arr = [ 
  {"name": "apple", "id": "apple_0"}, 
  {"name": "dog",   "id": "dog_1"}, 
  {"name": "cat", "id": "cat_2"}
];

addItem(arr, { "name": "apple", "id": "apple_0" });

addItem(arr, { "name": "pear", "id": "pear_3" });

console.log(arr);

And a bit shorter but less readable version:

    const addItem = (arr, item) => arr.find((x) => x.name === item.name) || arr.push(item); // you can also change `name` to `id`

    const arr = [ 
      {"name": "apple", "id": "apple_0"}, 
      {"name": "dog",   "id": "dog_1"}, 
      {"name": "cat", "id": "cat_2"}
    ];

    addItem(arr, { "name": "apple", "id": "apple_0" });

    addItem(arr, { "name": "pear", "id": "pear_3" });

    console.log(arr);

7
  • IMO, better to test it with ` === undefined`
    – Rayon
    Oct 19, 2016 at 17:43
  • Why - !undefined === true?
    – Ori Drori
    Oct 19, 2016 at 17:43
  • Readability is a good motive, but indeed it's a personal opinion. I'm going to add a shorter and less readable option :)
    – Ori Drori
    Oct 19, 2016 at 17:46
  • If it is an array as [0,1,2] and you are finding 0, in that case !0 === true;, In this particular context, your approach is fine :)
    – Rayon
    Oct 19, 2016 at 17:47
  • Indeed you're right, but not when dealing with objects.
    – Ori Drori
    Oct 19, 2016 at 17:49
5

Here is an other example with lodash

var a = [ {"name": "apple", "id": "apple_0"}, 
  {"name": "dog",   "id": "dog_1"}, 
  {"name": "cat", "id": "cat_2"}
]

var b = _.find(a, ['name', "apple2"]);

if(_.isObject(b)){
  console.log('exists')
}else{
    console.log('insert new')
}

https://jsfiddle.net/jorge182/s4og07jg/

5

This is what worked for me (after testing out the different solutions):

  addItem(items, item) {
    let foundObject = _.find(items, function(e) {
      return e.value === item.value;
    });

    if(!foundObject) {
      items.push(item);
    }
    return items;
  }
1

If you're interested in inserting in the array only one value, then using _.find could be an option. However, if you were interested in inserting one or more than one, I'd suggest using _.unionBy instead:

var currentArr = [{
    "name": "apple",
    "id": "apple_0"
  }, {
    "name": "dog",
    "id": "dog_1"
  }, {
    "name": "cat",
    "id": "cat_2"
  }],
  arrayOneValue = [{
    "name": "apple",
    "id": "apple_0"
  }],
  arrayTwoValues = arrayOneValue.concat({
    "name": "lemon",
    "id": "lemon_0"
  })

console.log(_.unionBy(currentArr, arrayOneValue, 'name'));
console.log(_.unionBy(currentArr, arrayTwoValues, 'name'));
// It also allow you to perform the union using more than one property
console.log(_.unionBy(currentArr, arrayTwoValues, 'name', 'id'));
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

1

Here are three ways of achieving this using lodash 4.17.5:

Say you want to add object entry to an array of objects numbers, only if entry does not exist already.

let numbers = [
    { to: 1, from: 2 },
    { to: 3, from: 4 },
    { to: 5, from: 6 },
    { to: 7, from: 8 },
    { to: 1, from: 2 } // intentionally added duplicate
];

let entry = { to: 1, from: 2 };

/* 
 * 1. This will return the *index of the first* element that matches:
 */
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0


/* 
 * 2. This will return the entry that matches. Even if the entry exists
 *    multiple time, it is only returned once.
 */
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}


/* 
 * 3. This will return an array of objects containing all the matches.
 *    If an entry exists multiple times, if is returned multiple times.
 */
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]


/* 
 * 4. This will return `true` if the entry exists, false otherwise.
 */
_.some(numbers, entry);
// output: true

If you want to return a Boolean (i.e., assuming that you are not using _.some()), in the first case, you can simply check the index value that is being returned:

_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true

Lodash documentation is great source of examples and experimentation.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.