如何在已声明的JSON对象中添加键值对

时间:2015-02-15 15:30:38

标签: javascript json

我已经声明了一个JSON对象并添加了一些键值对,如:

var obj  = {};

并在其中添加了一些数据,如:

obj = {
"1":"aa",
"2":"bb"
};

但是我想在同一个对象中添加更多的键值对,如果我添加上面提到的键值对,那么它将替换旧的键值对。那么任何人都可以告诉我如何在同一个JSON对象中添加数据,即obj。

8 个答案:

答案 0 :(得分:33)

您能否执行以下操作:

obj = {
    "1":"aa",
    "2":"bb"
};


var newNum = "3";
var newVal = "cc";


obj[newNum] = newVal;



alert(obj["3"]); // this would alert 'cc'

答案 1 :(得分:9)

您可以使用点表示法或括号表示法......

var obj = {};
obj = {
  "1": "aa",
  "2": "bb"
};

obj.another = "valuehere";
obj["3"] = "cc";

答案 2 :(得分:2)

您可以在同一个对象中添加更多键值对,而不必按以下方式替换旧键值:

var obj = {};

obj = {
"1": "aa",
"2": "bb"
};

obj["3"] = "cc";

以下是示例演示的代码和jsfiddle链接,它将在点击按钮时为已存在的obj添加更多键值对:

var obj = {
    "1": "aa",
    "2": "bb"
};

var noOfItems = Object.keys(obj).length;

$('#btnAddProperty').on('click', function() {
    noOfItems++;
    obj[noOfItems] = $.trim($('#txtName').val());
    console.log(obj);
});

https://jsfiddle.net/shrawanlakhe/78yd9a8L/4/

答案 3 :(得分:2)

请尝试在json上执行以下简单操作,插入/更新/推送:

var movie_json = {
                    "id": 100,
                 };

//to insert new key/value to movie_json
movie_json['name'] = 'Harry Potter';
console.log("new key: " + movie_json);

//to update a key/value in movie_json
movie_json['id'] = 101;
console.log("updated key: " +movie_json);

//adding a json array to movie_json and push a new item.
movie_json['movies']=["The Philosopher's Stone"];
movie_json['movies'].push('The Chamber of Secrets');
console.log(movie_json);

答案 4 :(得分:1)

您好我为每个对象添加键和值

let persons = [
  {
    name : "John Doe Sr",
    age: 30
  },{
    name: "John Doe Jr",
    age : 5
  }
]

function addKeyValue(obj, key, data){
  obj[key] = data;
}
 

let newinfo = persons.map(function(person) {
  return addKeyValue(person, 'newKey', 'newValue');
});

console.log(persons);

答案 5 :(得分:0)

可能重复,达到如下所述的最佳方式:

function getKey(key) {
  return `${key}`;
}

var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};

https://stackoverflow.com/a/47405116/3510511

答案 6 :(得分:0)

对象分配将一个或多个源对象复制到目标对象。所以我们可以在这里使用Object.assign

语法:Object.assign(target, ...sources)

var obj  = {};

Object.assign(obj, {"1":"aa", "2":"bb"})

console.log(obj)

答案 7 :(得分:0)

您可以尝试lodash

json对象的示例代码:

    var user = {'user':'barney','age':36};
    user["newKey"] = true;
    console.log(user);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>

用于json数组元素

示例代码:

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

users.map(i=>{i["newKey"] = true});

console.log(users);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>