0

How is that even possible that the value of widgets and newWidgets are same.

My program . look like this

var widgets = [{
    id: "1",
    title: 'title'
  },
  {
    id: "2",
    title: 'title2'
  },
  {
    id: "3",
    title: 'title3',
    children: [{
      id: "4",
      title: 'title4'
    }, {
      id: "5",
      title: 'title5',
      children: [{
          id: "6",
          title: 'title6'
        },
        {
          id: "7",
          title: 'title7'
        }
      ]
    }],
  },
  {
    id: "9",
    title: 'title9',
  }
]

var findAllObjectOnArray = function(obj) {
  for (var key in obj) {
    obj[key].newTitle = "newTitle" + key;
    if (obj[key].hasOwnProperty("children")) {
      findAllObjectOnArray(obj[key].children);
    }
  }
  return obj;
}
console.log(widgets)
let newWidgets = findAllObjectOnArray(widgets);
console.log(newWidgets);

ANy possible reason why console.log(widgets) and console.log(newWidgets) showing same result

prasanth
  • 22,145
  • 4
  • 29
  • 53
user2903536
  • 1,716
  • 18
  • 25
  • 3
    Because you change all the titles in widgets and then return it so newWidget IS widgets – mplungjan Mar 05 '20 at 10:02
  • @mplungjan, Initially i console.log then call the function and then again do the console.log . How is it possible that value changed even before calling the function ? – user2903536 Mar 05 '20 at 10:05
  • And browsers's logs hold a reference. Everytime you expand, they show the updated object/array. Use `console.log(JSON.parse(JSON.stringify(widgets)))` if you don't want the reference – adiga Mar 05 '20 at 10:06
  • console.log(widgets,newWidgets); after the change shows you it is the same object - see the dupe. Make a COPY first. You are not copying the widget, only making a new reference to the same object – mplungjan Mar 05 '20 at 10:07
  • https://hackernoon.com/please-stop-using-console-log-its-broken-b5d7d396cf15 "...Most of the time calling console.log() when the console is not yet active only results in a reference to the object being queued, not the output the console will contain. As a workaround you will need to either clone the information or serialize snapshots of it. The rendering happen asynchronously (being throttled to rate-limit updates), as future interactions with the logged objects like expanding object properties in the browser console." – kuklyy Mar 05 '20 at 10:08

0 Answers0