user6776038
user6776038

Reputation: 17

Search an array for a property value that is contained in another array

I am trying to pull an object from an array of objects that's property value is contained in my other array.

const myArrayOfObjects = [
 { value: 'test1' }
 { value: 'test2' }
]

const myArray = [ 'test1', 'test5' ];

const pluckedValue = myArrayOfObjects.find((item) => {
    let x;

     myArray.forEach((include) => {
         x = include === item.value ? include : undefined;
     });

     return item.value === x;
});

What I have works but it feels wrong. Is there a nicer way to accomplish this? Is this efficient? I have access to lodash and ES6 in my application.

Upvotes: 1

Views: 1188

Answers (4)

Redu
Redu

Reputation: 26161

One other way;

var myArrayOfObjects = [
                        { value: 'test1'},
                        { value: 'test2'}
                       ],
             myArray = [ 'test1', 'test5' ],
           something = [];

for (var obj of myArrayOfObjects) myArray.includes(obj.value) && something.push(obj);
console.log(something);

Upvotes: 0

Amit
Amit

Reputation: 46323

This is the ES2015 way:

const myArrayOfObjects = [
 { value: 'test1' },
 { value: 'test2' }
];

const myArray = [ 'test1', 'test5' ];

const pluckedValue = myArrayOfObjects.filter(item => myArray.includes(item.value));

console.log(pluckedValue);

Upvotes: 1

Niles Tanner
Niles Tanner

Reputation: 4021

I would use a find function if you want a single value:

myArrayOfObjects.find(function(include){
         return myArray.indexOf(include.value) !== -1;
     });

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Upvotes: 0

Tholle
Tholle

Reputation: 112777

You could just use a simple filter:

var result = myArrayOfObjects.filter(function (el) {
  return myArray.includes(el.value);
});

var myArrayOfObjects = [
 { value: 'test1' },
 { value: 'test2' }
];
var myArray = ['test1', 'test5'];

var result = myArrayOfObjects.filter(function (el) {
  return myArray.includes(el.value);
});

console.log(result);

Upvotes: 2

Related Questions