无法使用javascript在JSON对象中添加键值

时间:2017-12-24 03:52:49

标签: javascript json

我陷入了一个非常奇怪的问题。我之前已经这么做过很多次了,但这次它不起作用而且我被困住了。

driver.find_element_by_css_selector("h3[data-reactid=64]").text

输出如下: 输出如下:

对象{dummy:对象,虚拟键:"虚拟值"}

var updateObj = {};
db.child("symbols/" +name).once('value').then(function(data){
            if(data.exists())
                ticker.val().forEach(function(path){
                        addInJSON(path, data.val());
                });
            })
    //Trying to add some dummy values to test 
    addInJSON("dummy", {val: "pummy"});
    updateObj["dummykey"] = "dummy value";
    for(key in updateObj){
        console.log(key + "  " + updateObj[key]);
    }



function addInJSON(key, value){
    updateObj[key] = value;
}

问题

dummy:Object {val: "pummy"}
dummykey:"dummy value"
watchlist/41HJ5vonrUMMkH7TDwiSdAedhEL2/ADANIPOWER:Object {day_change: 2.25, day_change_percentage: 6.17, day_high: 40.05, …}
watchlist/41HJ5vonrUMMkH7TDwiSdAedhEL2/ARVIND:Object {day_change: -2.75, day_change_percentage: -0.6, day_high: 462.15, …}
watchlist/41HJ5vonrUMMkH7TDwiSdAedhEL2/ASHOKLEY:Object {day_change: 0.05, day_change_percentage: 0.04, day_high: 118.85, …}

1 个答案:

答案 0 :(得分:0)

add值设为objects,您可以执行此操作myObject['someKey'] = 'someValue'。但是如果你想以不同的方式添加值,我也为此添加了一个示例。请尝试snippet查看。

// Example 1
var myObject = {};

myObject['first'] = {};
myObject['second'] = {};

myObject['first']['firstFirst'] = 5;
myObject['first']['firstSecond'] = 6;
myObject['second']['secondFirst'] = 1;
myObject['second']['secondSecond'] = 9;

console.log("This is example 1.");
console.log(myObject);

// Example 2
var myObject2 = {};
Object.assign(myObject2, { first: { firstFirst: 5, firstSecond: 6 } });
Object.assign(myObject2, {second: { secondFirst: 1} });
Object.assign(myObject2['second'], { secondSecond: 9 });

console.log("\nThis is example 2");
console.log(myObject2);