darKnight
darKnight

Reputation: 6481

Filter values from two objects

Ok so this might seem simple, but somehow I am not getting the desired result here. I have two objects like this:

const parentObj = { a: "true", b: "true", c: "true", d: "true", e: "true" }
const childObj = { b : "true", e: "true" }

I want to compare these two objects, find common keys, and assign the value of common key from childObj to parentObj, so that I get the result:

{ a: "false", b: "true", c: "false", d: "false", e: "true" }

I tried this, but it's not working.

for (const parent in parentObj) {
    let valueFound = false;
    for (const child in childObj) {
        if (parent === child) {
            if (child === true) {
                parentObj[parent] = true;
                valueFound = true;
            }
        }
    }
    if (!valueFound) {
        parentObj[parent] = false;
    }
}

What's wrong here and what's the proper solution?

Upvotes: 0

Views: 51

Answers (3)

Jonas Wilms
Jonas Wilms

Reputation: 138307

Your code does work, if you replace child === true (which makes little sense as child is a key [string]) with childObj[child] === true. Or compare against "true" if you really want these booleans as strings. But your solution is quite slow, there is no need to iterate over the childObj and its keys, as you can just look up:

  for(let key in parentObj)
    parentObj[key] = childObj[key] === "true" ? "true" : "false";

Upvotes: 3

StepUp
StepUp

Reputation: 38134

Use Object.assign method:

  const parentObj = { a: true, b: false, c: true, d: true, e: false };
  const childObj = { b : true, e: true };

  const mergedObj =  Object.assign({}, parentObj, childObj);
  for (let key in mergedObj){
  if ( !childObj[key])
      mergedObj[key] = false;
  }

  console.log(mergedObj );

UPDATE:

Your code can be shortened. There is no need for the second loop. Because objects are dictionaries and you can always get O(N):

for (const parent in parentObj) {
    if ( child[parent])
        child[parent] = parentObj[parent];
    else    
        parentObj[parent] = false;    
}

Upvotes: 0

James Dullat
James Dullat

Reputation: 67

let parentObject = {
  a: true,
  b: false,
  c: true // not changed:- because its not present in child
}
let childObject = {
  b: false,
  a: false,
  f: true // ignored:- because its not available in parent
}
for(let cKey in childObject) {
  if(parentObject.hasOwnProperty(cKey)) {
    parentObject[cKey] = childObject[cKey];
  }
}

console.log(parentObject)

Upvotes: 0

Related Questions