0

so I am trying to add a property to an object if it doesn't already exist in the Object

so my code basically works

Psudo: (if the property doent exist in the object already add it in)

 var names= ["james", "kate", "kara", "milly"];
var storage = {}; 
var testElement = arr.pop(); 
  if(typeof(storage.testElement==='undefined')){  
    storage.testElement = '1';                    
  }
  else{
    storage.testElement = storage.testElement + 1; 
  }
return console.log(storage);

like I said this is sort of working, the output I get from the console log is { testElement: "1"} Where it says 'testElement' i need that to be the same as the item that was "popped" off the end of the array so in this case the last item in the array is "milly" so i need the object to say { milly: 1 } or { milly: "1" } Can anyone tell me how to change it?

1
  • thanks for all the answers you guys are thye best! Commented Jan 31, 2016 at 8:36

3 Answers 3

1

Please wrap your variable for the object access in []

storage[testElement]

and change the line to

if (typeof storage[testElement] === 'undefined') {  

otherwise you get the typeof of the comparison.

var names= ["james", "kate", "kara", "milly"];
var storage = {}; 
var testElement = names.pop(); 
if (typeof storage[testElement] === 'undefined') {
    storage[testElement] = '1';                    
} else {
    storage[testElement] = storage[testElement] + 1; 
}
document.write('<pre>' + JSON.stringify(storage, 0, 4) + '</pre>');

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

Comments

0

it should be

if(storage[testElement] === undefined)

and the working code, using hasOwnProperty to check property available or not then use [] notation to add/modify the property

var names= ["james", "kate", "kara", "milly"];
var storage = {}; 
var testElement = names.pop(); 
if(!storage.hasOwnProperty(testElement)){  
    storage[testElement] = '1';                    
}
else{
    storage[testElement] = storage[testElement] + 1; 
}
return console.log(storage);

Comments

0

Here is the fix to get result as you expect.

var names= ["james", "kate", "kara", "milly"];
var storage = {}; 
var testElement = names.pop(); 
  if(typeof storage[testElement] === 'undefined'){  
    storage[testElement] = '1';                    
  }
  else{
    storage[testElement] = storage[testElement] + 1; 
  }
console.log(storage);

2 Comments

Why you didn't change typeof(storage.testElement==='undefined') in if statement?
Yes, that needs to be changed.. It worked in the current case bcoz storage is empty.

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.