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

前端 未结 24 3210
情歌与酒
情歌与酒 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:18
    var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
        var injectObj = {isActive:true, timestamp:new Date()};
    
        // function to inject key values in all object of json array
    
        function injectKeyValueInArray (array, keyValues){
            return new Promise((resolve, reject) => {
                if (!array.length)
                    return resolve(array);
    
                array.forEach((object) => {
                    for (let key in keyValues) {
                        object[key] = keyValues[key]
                    }
                });
                resolve(array);
            })
        };
    
    //call function to inject json key value in all array object
        injectKeyValueInArray(arrOfObj,injectObj).then((newArrOfObj)=>{
            console.log(newArrOfObj);
        });
    

    Output like this:-

    [ { name: 'eve',
        isActive: true,
        timestamp: 2017-12-16T16:03:53.083Z },
      { name: 'john',
        isActive: true,
        timestamp: 2017-12-16T16:03:53.083Z },
      { name: 'jane',
        isActive: true,
        timestamp: 2017-12-16T16:03:53.083Z } ]
    
    0 讨论(0)
  • 2020-11-21 07:18

    Since its a question of the past but the problem of present. Would suggest one more solution: Just pass the key and values to the function and you will get a map object.

    var map = {};
    function addValueToMap(key, value) {
    map[key] = map[key] || [];
    map[key].push(value);
    }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-11-21 07:22

    I have grown fond of the LoDash / Underscore when writing larger projects.

    Adding by obj['key'] or obj.key are all solid pure JavaScript answers. However both of LoDash and Underscore libraries do provide many additional convenient functions when working with Objects and Arrays in general.

    .push() is for Arrays, not for objects.

    Depending what you are looking for, there are two specific functions that may be nice to utilize and give functionality similar to the the feel of arr.push(). For more info check the docs, they have some great examples there.

    _.merge (Lodash only)

    The second object will overwrite or add to the base object. undefined values are not copied.

    var obj = {key1: "value1", key2: "value2"};
    var obj2 = {key2:"value4", key3: "value3", key4: undefined};
    _.merge(obj, obj2);
    console.log(obj);
    // → {key1: "value1", key2: "value4", key3: "value3"} 
    

    _.extend / _.assign

    The second object will overwrite or add to the base object. undefined will be copied.

    var obj = {key1: "value1", key2: "value2"};
    var obj2 = {key2:"value4", key3: "value3", key4: undefined};
    _.extend(obj, obj2);
    console.log(obj);
    // → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}
    

    _.defaults

    The second object contains defaults that will be added to base object if they don't exist. undefined values will be copied if key already exists.

    var obj = {key3: "value3", key5: "value5"};
    var obj2 = {key1: "value1", key2:"value2", key3: "valueDefault", key4: "valueDefault", key5: undefined};
    _.defaults(obj, obj2);
    console.log(obj);
    // → {key3: "value3", key5: "value5", key1: "value1", key2: "value2", key4: "valueDefault"}
    

    $.extend

    In addition, it may be worthwhile mentioning jQuery.extend, it functions similar to _.merge and may be a better option if you already are using jQuery.

    The second object will overwrite or add to the base object. undefined values are not copied.

    var obj = {key1: "value1", key2: "value2"};
    var obj2 = {key2:"value4", key3: "value3", key4: undefined};
    $.extend(obj, obj2); 
    console.log(obj);
    // → {key1: "value1", key2: "value4", key3: "value3"}
    

    Object.assign()

    It may be worth mentioning the ES6/ ES2015 Object.assign, it functions similar to _.merge and may be the best option if you already are using an ES6/ES2015 polyfill like Babel if you want to polyfill yourself.

    The second object will overwrite or add to the base object. undefined will be copied.

    var obj = {key1: "value1", key2: "value2"};
    var obj2 = {key2:"value4", key3: "value3", key4: undefined};
    Object.assign(obj, obj2); 
    console.log(obj);
    // → {key1: "value1", key2: "value4", key3: "value3", key4: undefined}
    
    0 讨论(0)
  • 2020-11-21 07:23

    Simply adding properties:

    And we want to add prop2 : 2 to this object, these are the most convenient options:

    1. Dot operator: object.prop2 = 2;
    2. square brackets: object['prop2'] = 2;

    So which one do we use then?

    The dot operator is more clean syntax and should be used as a default (imo). However, the dot operator is not capable of adding dynamic keys to an object, which can be very useful in some cases. Here is an example:

    const obj = {
      prop1: 1
    }
    
    const key = Math.random() > 0.5 ? 'key1' : 'key2';
    
    obj[key] = 'this value has a dynamic key';
    
    console.log(obj);

    Merging objects:

    When we want to merge the properties of 2 objects these are the most convenient options:

    1. Object.assign(), takes a target object as an argument, and one or more source objects and will merge them together. For example:

    const object1 = {
      a: 1,
      b: 2,
    };
    
    const object2 = Object.assign({
      c: 3,
      d: 4
    }, object1);
    
    console.log(object2);

    1. Object spread operator ...

    const obj = {
      prop1: 1,
      prop2: 2
    }
    
    const newObj = {
      ...obj,
      prop3: 3,
      prop4: 4
    }
    
    console.log(newObj);

    Which one do we use?

    • The spread syntax is less verbose and has should be used as a default imo. Don't forgot to transpile this syntax to syntax which is supported by all browsers because it is relatively new.
    • Object.assign() is more dynamic because we have access to all objects which are passed in as arguments and can manipulate them before they get assigned to the new Object.
    0 讨论(0)
  • 2020-11-21 07:23

    supported by most of browsers, and it checks if object key available or not you want to add, if available it overides existing key value and it not available it add key with value

    example 1

    let my_object = {};
    
    // now i want to add something in it  
    
    my_object.red = "this is red color";
    
    // { red : "this is red color"}
    

    example 2

    let my_object = { inside_object : { car : "maruti" }}
    
    // now i want to add something inside object of my object 
    
    my_object.inside_object.plane = "JetKing";
    
    // { inside_object : { car : "maruti" , plane : "JetKing"} }
    

    example 3

    let my_object = { inside_object : { name : "abhishek" }}
    
    // now i want to add something inside object with new keys birth , gender 
    
    my_object.inside_object.birth = "8 Aug";
    my_object.inside_object.gender = "Male";
    
    
        // { inside_object : 
    //             { name : "abhishek",
    //               birth : "8 Aug",
    //               gender : "Male" 
    //            }   
    //       }
    
    0 讨论(0)
提交回复
热议问题