0

I would like to find values that are the same among javascript objects (perhaps later also add in a min , max statistic) I got stuck right at the start as my code returns some unexpected output (PS I am not looking for common properties, but for common properties that have the same values)

var obj1 = { "oranges": 5, "apples": 3, "peaches": 1 };
var obj2 = { "oranges": 4, "apples": 3, "peaches": 0 };
var obj3 = { "oranges": 5, "apples": 3, "peaches": 5 };
var obj_common = {};

for (var property in obj1) {
  if (obj1[property] = obj2[property])
    obj_common[property] = obj1[property];
}

console.log(obj_common);

3
  • 5
    Single "=" is assigning values to variables, == and === are logical (comparison) operators. Commented Sep 3, 2017 at 13:09
  • Possible duplicate of How to find common properties between JavaScript objects Commented Sep 3, 2017 at 13:22
  • Thx, I saw that question, but I am not looking for common properties, but for common properties with the same values :) Commented Sep 3, 2017 at 16:52

2 Answers 2

3

Use == or === for a comparison.

Explanation what your code does: The line (obj1[property] = obj2[property]) assigns the value of obj2[property] to obj1[property]. Because an assignment expression in javascript returns the assigned value, the expression evaluates to true for "oranges" and "apples" (because 4 and 3 are truthy values) and false for "peaches" (because 0 is a falsy value).

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

Comments

0

Please change = to == inside the if statement

  • = will assign value in right hand side to the variable in left hand side
  • == will compare value in both sides (eg 1=='1' gives true)
  • === use triple = if you want check both value and its type(1==='1' gives false)

var obj1 = { "oranges": 5, "apples": 3, "peaches": 1 };
var obj2 = { "oranges": 4, "apples": 3, "peaches": 0 };
var obj3 = { "oranges": 5, "apples": 3, "peaches": 5 };
var obj_common = {};

for (var property in obj1) {
  if (obj1[property] == obj2[property])
    obj_common[property] = obj1[property];
}

console.log(obj_common);

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.