0
  var mainObject = {
        a: "a",
        b: "b",
        c: "c",
        d: "d"
    }

var testObject = {
    a: "",
    b: ""
}

I want result like:

var testObject = {
    a: "a",
    b: "b"
}
3
  • Explain clearly Commented Jun 14, 2017 at 12:46
  • Assuming you know the keys of both objects, you could do testObject.a = mainObject.a and testObject.b = mainObject.b, but your question is really unclear so i'm not sure of what you want to achieve Commented Jun 14, 2017 at 12:50
  • Nah everytime i don't know the keys of both object. problem solved at the end thanks for reply Commented Jun 14, 2017 at 19:06

2 Answers 2

2

you can achieve this using for loop and hasOwnProperty function

var mainObject = {
        a: "a",
        b: "b",
        c: "c",
        d: "d"
    }

var testObject = {
    a: "",
    b: ""
}

for(keyOne in testObject){ 
  if(mainObject.hasOwnProperty(keyOne)){
     testObject[keyOne]= mainObject[keyOne]
  } 
}
console.log(testObject)

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

1 Comment

Thanks man, that's what i 'm looking for i got undefined somehow.
2

Is this what you are looking for...

var mainObject = {
        a: "a",
        b: "b",
        c: "c",
        d: "d"
    }
var testObject = {
    a: "",
    b: ""
}

for(var ob in mainObject){
if(Object.keys(testObject).indexOf(ob)!=-1)
    testObject[ob] = mainObject[ob]
}
console.log(testObject)

1 Comment

Yep, thanx dude.

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.