JavaScript object operations – How to add / remove item from a JavaScript object

Getting into JavaScript frameworks like vue.js and react.js, now it's time to review some of the JavaScript fundamentals.

 

How to remove item from a JavaScript object

Say I create an object as follows:

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI",
    "regex": "^http://.*"
};

What is the best way to remove the property regex to end up with new myObject as follows?

var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI"
};
var test = {'red':'#FF0000', 'blue':'#0000FF'};
delete test.blue; // or use => delete test['blue'];
console.log(test);

this deletes test.blue

 

There are two ways to add new properties to an object:

var obj = {
    key1: value1,
    key2: value2
};

Using dot notation:

obj.key3 = "value3";

Using square bracket notation:

obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]" 
How do I add a property to a JavaScript Object using a variable as the name?

You can use this equivalent syntax:

obj[name] = value;
 
How do I check if an object has a key in JavaScript? 

http://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript

Try the javascript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if keyis available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key')produces the result most code is looking for.

 

You'll have to iterate:

for (var k in obj) {
  if (!obj.hasOwnProperty(k)) continue;
  if (obj[k] === "orange") {
    /* yaay! an orange! */
  }
}

Now that "hasOwnProperty" test in there is to make sure you don't stumble over properties inherited from the prototype. That might not be desirable in some cases, and really it's one of the things you kind-of need to understand in order to know for sure whether you do or don't want to make that test. Properties that you pick up from an object's prototype can sometimes be things dropped there by various libraries. (I think the ES5 standard provides for ways to control whether such properties are "iterable", but in the real world there's still IE7.)

 

11.2.1 Property Accessors

I want to use the value of an objects property to name the property of another object. Easy to do in PHP:

$object1->property = 'name';
$object2->{$object1->property} = "value";
echo $object2->name; //outputs "value"

But in Javascript I can't figure out how to do this. The curly braces are used a different way.

Anyone know the php equivalent in javascript?

Thanks 🙂

object2[object1.property] = "value";

 

obj[type]

You use subscript notation.

11.2.1 Property Accessors

Properties are accessed by name, using either the dot notation:

MemberExpression . IdentifierName
CallExpression . IdentifierName

or the bracket notation:

MemberExpression [ Expression ]
CallExpression [ Expression ]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.