ANM
ANM

Reputation: 7

Updating an Object turns it to "undefined"

Here is a function I created which will update a particular object "collection"....

var collection = {
  "201301": {
    "Name": ["40x250x142"],
    "Age": ["41x59x129"]
  },
  "993736": {
    "Name": ["41x72x136"],
    "Age": ["61x79x592"]
  }
};
var copy = JSON.parse(JSON.stringify(collection));

function updateCollection(id, prop, value) {
  if (value === "") {
    delete collection[id][prop];
  } else if (prop === "Age") {
    collection[id][prop] = collection[id][prop] || [];
    collection[id][prop].push(value);
  } else {
    collection[id][prop] = value;
  }
}
console.log(updateCollection("993736", "Age", "42x6x259"));

For some reason whenever I try to update a property, the output is coming as "undefined"... What needs to be changed???

Upvotes: 0

Views: 143

Answers (2)

Avinash
Avinash

Reputation: 1118

    var collection = {
      "201301": {
        "Name": ["40x250x142"],
        "Age": ["41x59x129"]
      },
      "993736": {
        "Name": ["41x72x136"],
        "Age": ["61x79x592"]
      }
    };
    var copy = JSON.parse(JSON.stringify(collection));
    
    function updateCollection(id, prop, value) {
      if (value === "") {
        delete collection[id][prop];
      } else if (prop === "Age") {
        collection[id][prop] = collection[id][prop] || [];
        collection[id][prop].push(value);
      } else {
        collection[id][prop] = value;
      }
      return collection ; // Return the updated obj , if you want it from the method
    }
    console.log(updateCollection("993736", "Age", "42x6x259"));
     console.log("\n 2nd way ====> ",collection); // access it globally 

Upvotes: 0

Liftoff
Liftoff

Reputation: 25392

updateCollection() doesn't return anything, therefore, logging its result prints undefined.

Upvotes: 1

Related Questions