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

前端 未结 24 3382
情歌与酒
情歌与酒 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 } ]
    

提交回复
热议问题