0

I'm trying to go trough JS object (1) to find out if value exists on another object (2) and return object (2) found value.

var returnObj = [];
    selectedValues.forEach(function(value, key){
        var found = valuesObject.some(function (el) {
            if (el.item_id === value){
                return el.item_id;
            }
        });
        console.log(found);
    });

in this case I can only find out if its exists or not by getting true/false and I've also tried this

var returnObj = [];
    selectedValues.forEach(function(value, key){
        console.log(_.intersection(valuesObject, value));
    });

but in this case it returns me only empty arrays instead of object (2) value which was found by object (1) value

3 Answers 3

1

If you do a return inside of an .forEach call, you will only return out of the callback you passed to the forEach function, not your enclosing function. You can use a standard for-loop, where you can return out of.

Assuming you have a list of "values" you want to find in the second object:

const values = [/*...*/];

Object.keys(secondObject).forEach(key => {
  const value = secondObject[key];

  if (values.includes(value)) {
    /* secondObject has a property with the values you are looking for */
  }
});

Object.keys gives you an array of property keys of an object. Depending on your environment you can also use Object.values(), this will return you an array of values (not keys) for a given object.

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

1 Comment

but its still not answered how to find object property by value
1

Just keep it simple and basic:

for (var i = 0; i < selectedValues.length; i++) {
    for (var j = 0; j < valuesObject.length; j++) {
        if (selectedValues[i] === valuesObject[j].item_id) {
            return valuesObject[j].item_id;
        }
    }
}

If you prefer one line:

return selectedValues.length && selectedValues.map(value => valuesObject.find(v => v.item_id === value))[0]

2 Comments

yeah i think its the best solution since I was trying to find something faster
If you want something "shorter", I have added it to my answer. But it's not faster.
0

Perhaps I've got the setup wrong, but seeing returnObj is an array, filtering seems to be a good option. For example in combination with a Set:

let set = new Set(valuesObject.map(o=>o.item_id)),
    returnObj = selectedValues.filter(s=>set.has(s));

Example:

let selectedValues = ['aaa', 'bbb', 'ccc', 'ddd'],
	valuesObject = [ {item_id:'ddd'}, {item_id:'eee'}, {item_id:'bbb'}];


let set = new Set(valuesObject.map(o=>o.item_id)),
	returnObj = selectedValues.filter(s=>set.has(s));

console.log(returnObj);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.