将JSON对象中的数据推送到JSON对象数组

时间:2017-11-05 01:13:02

标签: javascript arrays json

我尝试使用JSON对象作为JSON对象数组中新默认值的来源。在我的第一次尝试中,我做到了这一点:

var records=
    [{"Key1":"ValueA","Key2":"ValueA","Key3":"ValueA"},
    {"Key1":"ValueB","Key2":"ValueB","Key3":"ValueB"}]

var defaultRecord =
    {"Key1":"DefaultValue1","Key2":"DefaultValue2","Key3":"DefaultValue3"}

pushNewDefaultRecord()
pushNewDefaultRecord()
changeFirstDefaultRecord("NEW VALUE")
showRecord()

function pushNewDefaultRecord(){
    records.push(defaultRecord)
}

function changeFirstDefaultRecord(newValue){
    records[2].Key1 = newValue
    records[2].Key2 = newValue
    records[2].Key3 = newValue
}

function showRecord(){
    console.log(JSON.stringify(records))
}

这会生成以下数组:

[{"Key1":"ValueA","Key2":"ValueA","Key3":"ValueA"},
{"Key1":"ValueB","Key2":"ValueB","Key3":"ValueB"},
{"Key1":"NEW VALUE","Key2":"NEW VALUE","Key3":"NEW VALUE"},
{"Key1":"NEW VALUE","Key2":"NEW VALUE","Key3":"NEW VALUE"}]

我意识到推送到记录数组的内容不是defaultRecord对象中的数据,而是对象本身,因此当我更新一条记录时,两条新记录都反映了这一变化。

更改pushNewDefaultRecord函数以使用JSON.stringify,然后使用JSON.parse,但看起来非常尴尬。是否有更清洁的方法来解决这个问题?

function pushNewDefaultRecord(){
    var newDefaultRecord = JSON.parse(JSON.stringify(defaultRecord))
    records.push(newDefaultRecord)
}

产地:

[{"Key1":"ValueA","Key2":"ValueA","Key3":"ValueA"},
{"Key1":"ValueB","Key2":"ValueB","Key3":"ValueB"},
{"Key1":"NEW VALUE","Key2":"NEW VALUE","Key3":"NEW VALUE"},
{"Key1":"DefaultValue1","Key2":"DefaultValue2","Key3":"DefaultValue3"}]

1 个答案:

答案 0 :(得分:0)

有两个功能。一个创建一个新记录,一个更改值。类似的东西:

class Solution {
private:
    unordered_map<int, long long> count_num;
public:
    int integerReplacement(int n) {
        count_num[1] = 0;count_num[2] = 1;count_num[3] = 2;
        if(!count_num.count(n)){
            if(n%2){
                count_num[n] = min( integerReplacement((n-1)/2), integerReplacement((n+1)/2) )+2;
            }else{
                count_num[n] = integerReplacement(n/2) +1;
            }
        }
        return(count_num[n]);
    }
};