1

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.

1
  • 2
    myArrayOfObjects.find((item) => myArray.includes(item.value) }); Commented Sep 20, 2016 at 21:05

4 Answers 4

2

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);

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

1 Comment

And to make it more ES6 (and slightly shorter) .filter(el => myArray.includes(el.value));
1

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);

Comments

0

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

Comments

0

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);

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.