-1

When I am trying to create a new object from the existing object as shown in below code i am unable to print the values from the duplicate object using JSON.stringify() method. Unable to figure out what is the problem.

<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object.</p>

<p id="demo"></p>

<script>
   var person = {firstName:"John2", lastName:"Doe", age:50, eyeColor:"blue"};
   var man = Object.create(person);
   document.getElementById("demo").innerHTML =
   man.firstName + " is " + man.age + " years old." + JSON.stringify(man);
</script>

</body>
</html>

Output I am getting is John2 is 50 years old. {}

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Satya Narayana
  • 454
  • 6
  • 20

2 Answers2

1

Check here

Object.create() takes an argument which sets the object as its prototype. It is used to create new object and extend another.

You should use Object.assign

var man = Object.assign({}, person);
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • For simple objects it is working fine, but for deep cloning i think we need to write our own logic. – Satya Narayana Jan 11 '17 at 05:54
  • yes.. this is a way to get shallow copy as per the question example..for deep copy you can check [here](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Suraj Rao Jan 11 '17 at 05:55
  • My requirement is something like below. I should be able to merge src1 and src2 as follows. src1={"name":"abc","desc":[[{"a":"b"}][{"c":"d"}][{"e":"f"}]]} and src2={"name":"abc","ver":1} to {"name":"abc","desc":[[{"a":"b"}][{"c":"d"}][{"e":"f"}]],"ver":1} and i am not using jquery – Satya Narayana Jan 11 '17 at 05:58
0

I achieved the desired result as follows. how to use javascript Object.defineProperty link helped me in resolving my issue.

//check whether property name of v exists in v1.
    Object.getOwnPropertyNames(v[0]).forEach(function(val,idx,array){
        console.log(val + '->' + v[0][val]);
        if (val !== undefined && val !== "_id" && !v1[0].hasOwnProperty(val)) {
                Object.defineProperty(v1[0], val, {enumerable:true,configurable:false,get:function(){return v[0][val];}});
        }
    });     
Community
  • 1
  • 1
Satya Narayana
  • 454
  • 6
  • 20