简体   繁体   中英

How do I add an object property via an argument?

function addPropertyToProduct(product, property, value) {
  let tryThis = property;

  product.tryThis = value;

  return product;
}

The argument 'product' will be an object that looks like this:

{ type: 'Terminator 2: Judgement Day', price: '£6.99', quantity: 1 }

Given a 'property' as an argument, as well as its corresponding value, update the 'product' to include this new information. Then return the updated 'product'.

Eg if given the 'property' 'length' and the value '2h 36m', your function should return

{ type: 'Terminator 2: Judgement Day', price: '£6.99', quantity: 1, length: '2h 36m' }

This is the answer I'm receiving:

 **+ expected** *- actual*

       {
      **+  "length": "2h 36m"**
         "price": "£6.99"
         "quantity": 1
      *-  "tryThis": "2h 36m"*
         "type": "Terminator 2: Judgement Day"
       }

This returns the value correctly but names the key as the variable name, not the argument itself?

Use square brackets [] :

function addPropertyToProduct(product, property, value) {
  let tryThis = property;

  product[tryThis] = value;

  return product;
}

For more info, check: MDN Computed Property Names

function addProperty(obj,propertyName,value){

      obj.propertyName = value;
      return obj;

}

This function will simply create a property dynamically and add value to it. hope it helped.

NB: you can also use the spread operator instead of assigning 'product' to a new variable inside your function. But, yes in general, "Computed Property Names" is the key as Alvaro is saying above:)

function addPropertyToProduct(product, property, value) {
  return {
    ...product,
    [property]: value
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM