How can I add a key/value pair to a JavaScript object?

前端 未结 24 3344
情歌与酒
情歌与酒 2020-11-21 07:01

Here is my object literal:

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

How can I add field key3 with value3 to the ob

24条回答
  •  长发绾君心
    2020-11-21 07:21

    Performance

    Today 2020.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v78.0.0, Safari v13.0.4 and Firefox v71.0.0, for chosen solutions. I divide solutions to mutable (first letter M) and immutable (first letter I). I also provide few immutable solutions (IB,IC,ID/IE) not yet published in answers to this question

    Conclusions

    • fastest mutable solutions are much faster than fastest immutable (>10x)
    • classic mutable approach like obj.key3 = "abc" (MA,MB) is fastest
    • for immutable solutions the {...obj, key3:'abc'} and Object.assign (IA,IB) are fastest
    • surprisingly there are immutable solutions faster than some mutable solutions for chrome (MC-IA) and safari (MD-IB)

    Details

    In snippet below there are presended tested solution, you can prefrom test on your machine HERE

    var o = {
        key1: true,
        key2: 3,
    };
    
    var log= (s,f)=> console.log(`${s} --> ${JSON.stringify(f({...o}))}`);
    
    
    
    function MA(obj) {
      obj.key3 = "abc";
      return obj;
    }
    
    function MB(obj) {
      obj['key3'] = "abc";
      return obj;
    }
    
    function MC(obj) {
      Object.assign(obj, {key3:'abc'});
      return obj;
    }
    
    function MD(obj) {
      Object.defineProperty(obj, 'key3', {
        value: "abc",       // undefined by default
        enumerable: true,      // false by default
        configurable: true,    // false by default
        writable: true         // false by default
      });
      return obj;
    }
    
    function IA(obj) {
      return {...obj, key3:'abc'};
    }
    
    function IB(obj) {
      return Object.assign({key3:'abc'}, obj);
    }
    
    function IC(obj) {
      let ob= JSON.parse(JSON.stringify(obj))
      ob.key3 = 'abc';
      return ob;
    }
    
    
    function ID(obj) {
    	let ob= Object.fromEntries(Object.entries(obj));
      ob.key3 = 'abc';
      return ob;
    }
    
    function IE(obj) {
    	return Object.fromEntries(Object.entries(obj).concat([['key3','abc']]))
    }
    
    
    
    log('MA',MA);
    log('MB',MB);
    log('MC',MC);
    log('MD',MD);
    log('IA',IA);
    log('IB',IB);
    log('IC',IC);
    log('ID',ID);
    log('IE',IE);
    This snippet only presents code - it not perform tests itself!

提交回复
热议问题